shira stenmetz
shira stenmetz

Reputation: 293

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.

Upvotes: 1

Views: 49

Answers (2)

shira stenmetz
shira stenmetz

Reputation: 293

So why this query doesnt work?

Like.aggregate({ $group: { _id: "$idPost", totalNumLikes: { $sum: 1 } } }, function (err, likesResult) {
    if (err) {
        console.log("error in app.post(numlikesforUser)")
        return res.send(err);
    }
    Post.find({idPost: {$in: likesResult.map(r => r._id)}, "emailPublisher": req.body.emailUser }, function (err, posts) {
    for (var i =0; i < likesResult.length; i++) {
         var result = likesResult[i]; 
         var post = posts.filter(p => p._id === result._id)[0];
         if (post != null) {
                likesCount = likesCount + result.totalNumLikes
            }
        }
    console.log("likescount is:::::::::::::" + likesCount);
   });
});

Upvotes: 0

Amiram Korach
Amiram Korach

Reputation: 13296

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.

Upvotes: 1

Related Questions