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.