Search code examples
javascriptnode.jsmongodbnode-mongodb-native

MongoDB / Javascript Scope Issue


I'm connecting and making an insert with Node/MongoDB, but due to a scope issue, I can't access the connection from the function. Any idea how to make the 'db' variable global scope?

mongodb.connect("mongodb://localhost:27017/userDB", function(err, db) {

   if(!err) {
       console.log("We are connected");
   } else {
       console.log(err);
   }

});

function RegisterUser(user, pass) {
    var collection = db.collection('users');
    var docs = [{username:user}, {password: pass}];
    collection.insert(docs, {w:1}, function(err, result) {
        collection.find().toArray(function(err, items) {});
        socket.emit('message', items);
    });
}

/var/www/baseball/app.js:80
    var collection = db.collection('users');  <--db is not defined
                     ^
ReferenceError: db is not defined
at RegisterUser (/var/www/baseball/app.js:80:20)
at ParseData (/var/www/baseball/app.js:63:6)

Solution

  • In general, only make the connection once, probably as you app starts up. The mongo driver will handle pooling etc., at least, so I was told by experts from MongoLabs. Note that this is very different than what you might do in Java, etc... Save the db value returned by connect() somewhere, perhaps a global or in app, or in a commonly used one of your modules. Then use it as needed in RegisterUser, DeleteUser, etc.