node.js MongoDB查询不返回结果

问题描述:

我正在玩弄mongodb,并在“用户”集合中输入了一些测试数据{name:“david”}。我验证了数据在MongoDB中使用蒙戈外壳通过键入node.js MongoDB查询不返回结果

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返回。请告知

你实际上关闭数据库连接从收集的数据已返回之前。

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(); 
    }); 
}); 

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

在db.collection和connection.find调用中,你没有检查err和处理。你只是在公开电话会议上做。

此外,如果您打开connection pool option(您不想在每次调用时打开和关闭连接),则不应该调用db.close()。如果您确实想关闭,请在回调中关闭。

喜欢的东西:

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

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

正如CJohn所述,您正在关闭数据库连接,然后才能检索数据。我知道它看起来不像,但是Node结构和回调就是这种情况。正确处理此问题的代码是:

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 -g n 
sudo n stable 

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