简体   繁体   中英

Unable to deploy nodejs-mongodb project on heroku

My connection file looks like this:

var mongo       = require('mongodb');
var dbName      = 'KrishiMoney';
var mongoUri    = process.env.MONGOLAB_URI


/* establish the database connection */

var db ;
mongo.MongoClient.connect(mongoUri, {server:{auto_reconnect:true}}, function (err,database){
if (err) {
        console.log(e);
    }   else{
        //console.log('connected to database :: ' );
        db = database;
    }

});

var accounts = db.collection('accounts');

This gives the following error:

var accounts = db.collection('accounts'); ^ at Object.Module._extensions..js (module.js:467:10) TypeError: Cannot call method 'collection' of undefined

My guess is that the db variable is not getting correct value. What is the correct way to populate the db variable when connecting using MongoClient?

The callback function you pass to the MongoClient.connect method will be executed asynchronously after the connection is established so at the point when you call db.collection('accounts') db variable is undefined.

Try wrapping the rest of your code which works with the database inside the callback function, which will make sure it is executed after the connection is established

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM