Reputation: 498
With the following function i get all articles:
getAllPost: (req, res) => {
Article.find({}).limit().populate('author').then(articles => {
res.render('home/AllPost',{
articles
});
});
}
I want do display the articles of current logged in user but im not sure how can i do it ?
Upvotes: 1
Views: 18
Reputation: 103455
Use the aggregate()
method to run a pipeline that has a $lookup stage
to do a "left-join" on the articles
collection for a particular user. Consider the following example:
getAllPost: (req, res) => {
User.aggregate([
/* filter users collection for current user given by req.user._id */
{ "$match": { "_id": mongoose.Types.Objectid(req.user._id) } },
/* perform a "left-join" to the articles collection
and store the results in an array "articles"
*/
{
"$lookup": {
"from": "articles",
"localField": "_id",
"foreignField": "author",
"as": "articles"
}
}
]).exec().then(results => {
let articles;
if (!results.length) {
articles = [];
} else {
articles = results[0].articles;
}
res.render('home/AllPost', { articles });
})
}
Upvotes: 1