简体   繁体   English

无法从集合中检索数据

[英]Can't retrieve data from collection

My problem is that I can't retrieve data from my mongodb database... And I don't know why. 我的问题是我无法从mongodb数据库中检索数据……而且我也不知道为什么。

I probably do something wrong, here is a little samble which doesn't work. 我可能做错了什么,这是一个无效的小词。

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

Notice that I have data in my database as shows the following 请注意,我的数据库中有数据,如下所示

➜  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") }

Thanks for help ! 感谢帮助 !

Notice: the example program never ends, I don't know why... Maybe because the connection is never closed but if I call the db.close() in the toArray callback, It will never be called because the callback never happends. 注意:示例程序永远不会结束,我不知道为什么...也许是因为连接从未关闭,但是如果我在toArray回调中调用db.close() ,它将永远不会被调用,因为回调从未发生。

So many things in node are asynchronous. 节点中的许多东西都是异步的。 Your connection is open after you are trying to read from your collection. 尝试从您的收藏集中阅读后,您的连接已打开。

You should query the collection after you know for sure you are connect. 在确定可以连接后,应该查询集合。 Down and dirty: 羽绒服:

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

I ran this locally and received back the "hello" message. 我在本地运行此消息,并收到了“ hello”消息。 Also your script never finishes because the node process will run until it is closed or crashes. 另外,脚本将永远不会结束,因为节点进程将一直运行,直到它关闭或崩溃。 This is by design. 这是设计使然。 Which also means that you don't have to keep opening and closing your mongo connections. 这也意味着您不必继续打开和关闭mongo连接。 You can open a connection when your application starts and close it when your application is shut down. 您可以在应用程序启动时打开连接,而在应用程序关闭时关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM