0

I am trying to store the connection item inside a variable so that I can reuse it on other methods that perform insertion, deletion, etc.

var MongoClient = require('mongodb').MongoClient;

let _db;

connect = function () {
    MongoClient.connect("mongodb://localhost:27017", {useNewUrlParser: true}, function (err, client) {
        _db = client.db("SomeDB");
    });
};

addTestCollection = function () {
    _db.collection('Persons', function (err, collection) {

        collection.insertOne({id: 1, firstName: 'Steve', lastName: 'Jobs'});
        collection.insertOne({id: 2, firstName: 'Bill', lastName: 'Gates'});
        collection.insertOne({id: 3, firstName: 'James', lastName: 'Bond'});

        _db.collection('Persons').count(function (err, count) {
            if (err) throw err;

            console.log('Total Rows: ' + count);
        });
    });
};

connect();
addTestCollection();

The line that attempts to create the collection "Persons" returns a "Cannot read property 'collection' of undefined" error.

  • connect() function has async callback, so you access _db variable before it is assigned. – l2ysho Jun 23 '19 at 14:52
  • Hello @RichardSolár Thank you for your response. Do you have any recommendation on how the code should be altered in order to retrieve the connection and reuse it for other purposes? –  Jun 23 '19 at 15:00
  • Welcome to JS - Callback World! As you can see, almost async functions in js are callback functions, just code js with js rule. Why you need a different way? – hoangdv Jun 23 '19 at 17:18
  • @GeorgiosG. I recommend you to use utils.promisify and handle connection as a promise or in a async/await. Look at this https://stackoverflow.com/questions/23771853/how-can-i-promisify-the-mongodb-native-javascript-driver-using-bluebird – l2ysho Jun 23 '19 at 18:58

0 Answers0