[英]nodejs + mongodb - find empty
I'm trying to find all rows where post_id is the same as I'm searching for. 我正在尝试查找post_id与我搜索的行相同的所有行。 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. EDIT1:代码已更新。
The love
in that callback is a cursor, not the array of docs. 该love
在回调是一个游标,而不是文档的数组。 To make it an array, call toArray
like you are in your first query; 要使其成为数组,请像在第一个查询中一样调用toArray
; 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. 另外,您的下一个问题很可能是您的res.send
调用将不包含任何love
文档,因为它发生在任何love
回调之前。 You need to delay calling res.send
until all callbacks have been received. 您需要延迟调用res.send
直到收到所有回调。 You can do that by keeping a count of outstanding callbacks or using an async flow control module like async
. 您可以通过保留未完成的回调计数或使用异步流控制模块(例如async
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.