简体   繁体   中英

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.

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.

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. 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. You can open a connection when your application starts and close it when your application is shut down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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