I have the following aggregation Query in my application:
const posts = await Post.aggregate([
{ $match: { creator: { $in: req.body.following} } },
{
$lookup: {
from: "users",
localField: "creator",
foreignField: "_id",
as: "creatorDoc",
pipeline: [
{
$lookup: {
// references stories collection
from: "stories",
pipeline: [
{
// The match below should find the story document with the _id equal to the last id
// stored inside the stories array attatched to creator documents
$match: {
$expr: {
$eq: [
"$_id",
{ $arrayElemAt: ["$creatorDoc.stories", -1] },
],
},
},
},
],
as: "stories",
},
},
],
},
},
{
$unwind: "$creatorDoc",
},
{
$project: {
creator: "$creatorDoc.username",
// No stories property is returned in the response object
stories: "$stories",
isLiked: { $in: [new mongoose.Types.ObjectId(req.user._id), "$likedBy"] },
createdAt: 1,
},
},
])
The above query returns posts that meet the $match
criteria. I use a $lookup
on the creator
field of the post in order to return the creator’s user information.
Each creatorDoc
has an array called stories
which references documents in the Story
collection. In the query, I try to $lookup
only the last story, by matching a story documents _id
to the last id
stored in creatorDoc.stories
. This should return a stories
array containing information regarding only the last story the creator has.
However, inside the result, there is no stories attribute at all. I have also tried to $unwind
stories, however this doesn’t accomplish anything. Any ideas why this code is not working? Thanks