0

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 :/
uncool
  • 2,613
  • 7
  • 26
  • 55
  • 1
    The key thing to notice in your results here is that `undefined` is printed *before* the object is printed. This is because the `connect` function is asynchronous. It's successfully setting the `db` value, it's just doing so *after* you try to print it outside of that operation. – David Sep 11 '20 at 14:35
  • I see! Thank you! :) – uncool Sep 11 '20 at 14:36

0 Answers0