Reputation: 6946
I am trying to use $match in mongoose aggregate query.
Feed.aggregate([
{$match:{"createdBy":'ObjectId("59d79b6ea918cf1e40ee041f")'}},
{
"$lookup":
{
"from": "comments",
"localField": "_id",
"foreignField": "feedId",
"as": "feedComment"
}
}
]).exec(function(err, results){
if(err){
res.json({"success": false,"errorCode": errorCodes.serverError,"error": err});
}else{
if(results == null){
res.json({"success": false,"errorCode": errorCodes.dataNotFound,"error": "no record found"})
}else{
res.json({"success": true,"data": results});
}
}
})
It is giving black results array.
But without $match it works.
The feeds collection is:
{
"_id" : ObjectId("59d878f67e6ba32c60c7410c"),
"createdBy" : ObjectId("59d79b6ea918cf1e40ee041f"),
"feedKeywords" : "school,kids",
"feedDescription" : "Going to school",
"feedTitle" : "Going to schoo",
"updatedAt" : ISODate("2017-10-07T06:49:26.100Z"),
"createdAt" : ISODate("2017-10-07T06:49:26.100Z"),
"__v" : 0
}
Comments collection is like this
{
"_id" : ObjectId("59d87a737e6ba32c60c7410e"),
"createdBy" : ObjectId("59d6562dd3c2be2ba452665e"),
"feedId" : ObjectId("59d878f67e6ba32c60c7410c"),
"stars" : "3.5",
"commentText" : "vewr nice",
"updatedAt" : ISODate("2017-10-07T06:55:47.305Z"),
"createdAt" : ISODate("2017-10-07T06:55:47.305Z"),
"__v" : 0
}
Upvotes: 0
Views: 1582
Reputation: 5476
You have used Single Quote for the value of createdBy in the $match aggregation pipeline, so that the value would be treated as String but the data in your Feed collection for createdBy is an Object and hence the there is no data retrieved when the $match is added.
Please use this corrected query
Feed.aggregate([
{$match:{"createdBy":new mongoose.Types.ObjectId("59d79b6ea918cf1e40ee041f")}},
{
"$lookup":
{
"from": "comments",
"localField": "_id",
"foreignField": "feedId",
"as": "feedComment"
}
}
]).exec(function(err, results){
if(err){
res.json({"success": false,"errorCode": errorCodes.serverError,"error": err});
}else{
if(results == null){
res.json({"success": false,"errorCode": errorCodes.dataNotFound,"error": "no record found"})
}else{
res.json({"success": true,"data": results});
}
}
})
Upvotes: 1