Nodejs - mongodb - Unable to call 'collection' null method

I try to query the database every time the user enters messages, nodejs complains: "Cannot call collection method" null "Below is the code that I think the problem is.

var mongo = require('mongodb'); var db = new mongo.Db('chat', new mongo.Server('127.0.0.1', '27017', {native_parser:true})); //testting querying mongo everytime there is message socket.on('connection', function(client) { client.on('message', function(message) { db.open(function(err, db){ db.collection('sessions', function(err, collection){ collection.count(function(err, count) { sys.puts("There are " + count + " records."); }); }); }); }); }); 

note: the first message from the user, I received the correct number of sys.puts, no errors. but the second input will cause an error.

+4
source share
2 answers
 db.open(function(err, db){ socket.on('connection', function(client) { }); }); }); 

As Reinos said, the db.open proposal in the external closure will solve the problem.

+2
source
 db.open(function(err, db){ if (err) { sys.puts(err); } else { db.collection('sessions', function(err, collection){ collection.count(function(err, count) { sys.puts("There are " + count + " records."); }); }); } }); 

Always check the err object and print it.

+3
source

All Articles