简体   繁体   中英

nodejs + mongodb - find empty

I'm trying to find all rows where post_id is the same as I'm searching for. But every time I do the result is empty, and I've double check all values and I should get some result.

This is the method I'm using:

db.collection('posts', function(err, collection) {
    collection.find({}, {}, {limit:100}).toArray(function(err, posts) {
        if (err) res.send({'error':1,'message':'error getting all posts'});
        console.log('Number of posts: ' + posts.length);
        posts.forEach(function(entry) {
            db.collection('love', function(err, collection) {
                collection.find({}, function(err, love) {
                    if (err) console.log(err);
                    if (!love) console.log("empty");
                    if (love) {
                        console.log(love);
                        entry.love = love;
                    }
                });
            });
        });
        res.send(JSON.stringify(posts));
    });
});

It always enter the third if like if I have a result but in the console I always get [] from the result. Any idea of that I'm doing wrong?

EDIT1: Code updated.

The love in that callback is a cursor, not the array of docs. To make it an array, call toArray like you are in your first query; like this:

collection.find({}).toArray(function(err, love) {
    if (err) console.log(err);
    if (!love) console.log("empty");
    if (love) {
        console.log(love);
        entry.love = love;
    }
});

Also, your next problem will likely be that your res.send call won't include any of the love docs because it's happening before any of the love callbacks. You need to delay calling res.send until all callbacks have been received. You can do that by keeping a count of outstanding callbacks or using an async flow control module like async .

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