shira stenmetz shira stenmetz - 4 months ago 15
Javascript Question

Explain the output of a mongoose query

Can someone explain to me why, when I execute the following code,I get an empty list?

Post.find({ "emailPublisher": req.body.emailUser }, { _id: 0, "idPost": 1 }, function (err, idsposts) {
console.log(idsposts)
for (i in idsposts) { list.push(idsposts[i].idPost) }
});
console.log("list is " + list);


It seems like this line:

console.log("list is " + list);


occurs before the find query.

Answer

You need to insert it in the callback:

Post.find({ "emailPublisher": req.body.emailUser }, { _id: 0, "idPost": 1 }, function (err, idsposts) {
    console.log(idsposts)
    for (i in idsposts) { list.push(idsposts[i].idPost) }
    console.log("list is " + list);
});

find is an async operation.

Comments