node.js MongoDB查询不返回结果

我正在玩MongoDB,并在“用户”集合中input了一些testing数据{name:“david”}。 我通过键入来validation数据是在MongoDB中使用mongo shell

db.users.find() 

结果:

 { "name":"david" } 

在node.js脚本中,下面的代码:

 db.open(function(err, db) { if (!err) { console.log("db opened!"); } else { console.log(err); } db.collection('users', function(err, collection) { collection.find({}, function(err, cursor) { cursor.each(function(err, item) { console.log(item); }); }); }); db.close(); }); 

不会返回任何结果

我没有看到任何错误,没有err返回。 请指教

实际上,在集合中的数据返回之前,您正在closures数据库连接。

 db.collection('users', function(err, collection) { collection.find({}, function(err, cursor) { cursor.each(function(err, item) { console.log(item); }); // our collection has returned, now we can close the database db.close(); }); }); 

正如CJohn所说的,你正在closures数据库连接之前,你检索数据。 我知道它看起来不像,但是Node结构和callback就是这种情况。 正确处理这个问题的代码是:

 db.open(function(err, db) { if (err) return console.log('error opening db, err = ', err); console.log("db opened!"); db.collection('users', function(err, collection) { if (err) return console.log('error opening users collection, err = ', err); collection.find({}, function(err, cursor) { if (err) return console.log('error initiating find on users, err = ', err); cursor.each(function(err, item) { // watch for both errors and the end of the data if (err || ! item) { // display (or do something more interesting) with the error if (err) console.log('error walking data, err = ', err); // close the connection when done OR on error db.close(); return; } console.log(item); }); }); }); }); 

尝试将节点升级到最新版本。

 sudo npm cache clean -f sudo npm install -gn sudo n stable 

版本0.4可能无法正常工作。

这个模式在我的节点/ mongo示例中工作正常。 该函数传递一个callback函数,该函数接受err,collection。 它获取“用户”集合,如果成功,调用将查找集合并将其转换为数组,但是您也可以在光标上进行迭代。

在db.collection和connection.find调用中,你不检查错误和处理。 你只是公开的电话。

另外,你不应该调用db.close(),特别是如果你打开连接池选项 (你不想在每次调用时打开和closures连接)。 如果你想closures,那么closurescallback。

就像是:

 var server = new Server(host, port, {auto_reconnect: true, poolSize: 5}, {}); MyStore.prototype.getUsers = function(callback) { server.open(function(err, db) { if (err) { callback(err); } else { db.collection('users', function(err, collection) { if( err ) callback(err); else { collection.find().toArray(function(err, users) { if (err) { callback(err) } else { callback(null, users); } }); } } }}); 

这里是另一个节点+ mongo的教程,可以帮助: http : //howtonode.org/express-mongodb