Node.js Can';无法从集合中检索数据

Node.js Can';无法从集合中检索数据,node.js,mongodb,Node.js,Mongodb,我的问题是我无法从mongodb数据库检索数据。。。我不知道为什么 我可能做错了什么,这里有一个小samble不起作用 var Db = require('mongodb').Db, Server = require('mongodb').Server; var db = new Db('akemichat', new Server('localhost', 27017), {w:1}); db.open(function (err, p_db) {

我的问题是我无法从mongodb数据库检索数据。。。我不知道为什么

我可能做错了什么,这里有一个小samble不起作用

var Db          = require('mongodb').Db,
    Server      = require('mongodb').Server;


var db = new Db('akemichat', new Server('localhost', 27017), {w:1});
db.open(function (err, p_db) {
    db = p_db;
});


db.collection('rooms', function (err, collection) {
    if (!err) {
        collection.find().toArray(function(err, items) {
            items.forEach(function(room) {
                console.log('hello'); // Never call...
            });
        });
    } else {
        console.log(err);
    }
});
注意,我的数据库中有如下所示的数据

➜  akemichat git:(master) ✗ mongo
MongoDB shell version: 2.4.7
connecting to: test
> use akemichat
switched to db akemichat
> db.rooms.find()
{ "name" : "home", "_id" : ObjectId("527008e850305d1b7d000001") }
谢谢你的帮助


注意:示例程序永远不会结束,我不知道为什么。。。可能是因为连接从未关闭,但如果我在
toArray
回调中调用
db.close()
,它将永远不会被调用,因为回调从未发生。

节点中的许多事情都是异步的。尝试读取收藏后,连接已打开

您应该在确定已连接后查询集合。脏兮兮的:

var Db          = require('mongodb').Db,
    Server      = require('mongodb').Server;


var db = new Db('akemichat', new Server('localhost', 27017), {w:1});
db.open(function (err, p_db) {
    db = p_db;

    db.collection('rooms', function (err, collection) {
        if (!err) {
            collection.find().toArray(function(err, items) {
                items.forEach(function(room) {
                    console.log('hello'); // Never call...
                });
            });
        } else {
            console.log(err);
        }
    });
});

我在本地运行了这个程序,并收到了“hello”消息。此外,脚本永远不会完成,因为节点进程将一直运行,直到关闭或崩溃。这是故意的。这也意味着你不必一直打开和关闭你的mongo连接。您可以在应用程序启动时打开连接,在应用程序关闭时关闭连接。

尝试将收藏
find
移动到
事件回调的回调中。