我试图在每次用户输入消息时查询数据库,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计数,没有错误。但第二个输入会导致错误。
答案 0 :(得分:3)
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
对象并进行打印。
答案 1 :(得分:2)
db.open(function(err, db){
socket.on('connection', function(client) {
});
});
});
由于Raynos建议将db.open置于闭包外部将解决问题。