I’m trying to query database everytime users input messages, nodejs complains “Cannot call method ‘collection’ of null” Below is the code I think the problem comes from.
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 user’s message, I got the sys.puts count right, no errors. but the second input will cause error.
As Raynos suggested putting db.open in outer of closure will solve the problem.