I'm trying to create a pooled connection object with MongoDB
as per http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html however my code behaves in an unexpected manner.
Needless to say I'm fairly new to Javascript and Node.js... and my intended pool variable (db
) is undefined
even though I assigned it within the .connect
statement. How can the db
be empty (undefined
) outside the MongoClient.connect
statement although it got assigned alright within the statement?
const MongoClient = require('mongodb').MongoClient;
const connOptions = {useNewUrlParser: true, useUnifiedTopology: true}
const connString = 'mongodb+srv://Master:mypass@' +
'cluster0.vpss6.mongodb.net/' +
'sample_analytics?retryWrites=true&w=majority'
var db
MongoClient.connect(connString, connOptions, function(err, database) {
if (err) throw err
db = database
console.log(db) // prints an object
})
console.log(db) // prints undefined :/