nodejs – mongodb – 无法调用null的方法“集合”

我试图查询数据库每次用户input消息,nodejs抱怨“不能调用方法'收集'null”下面是我认为这个问题的代码来自。

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."); }); }); }); }); }); 

注意:第一个用户的消息,我得到了sys.puts计数正确,没有错误。 但第二个input会导致错误。

 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."); }); }); } }); 

始终检查err对象并打印出来。

 db.open(function(err, db){ socket.on('connection', function(client) { }); }); }); 

由于Raynosbuild议将db.open放在闭包外面将解决问题。