I have the following two tables :
Comments :
{
"createdOn": "2020-03-08T04:19:20.276Z",
"comment": "First comment in the app",
"likesCount": 1,
"_id": "5e6472c32fe18a59b1068f46",
"userId": "5e60ec371dc3d30e61c6805b",
"postId": "5e6356546d284c2cdfe1ad92",
"__v": 0
}
CommentLikes :
{
"createdOn": "2020-03-08T06:47:58.855Z",
"_id": "5e64955abb6056610f802159",
"userId": "5e60ec371dc3d30e61c6805b",
"commentId": "5e6472c32fe18a59b1068f46",
"__v": 0
}
Now i am trying to get all the likes with following query :-
Comments.aggregate([
{$match: {postId : postId}},
{$lookup:{
from: 'commentLikes',
localField: '_id',
foreignField: 'commentId',
as : 'likes'
}}
])
.exec()
It is not returning any like. Response I get from this query is :-
{
"_id": "5e6472c32fe18a59b1068f46",
"createdOn": "2020-03-08T04:19:20.276Z",
"comment": "First comment in the app",
"likesCount": 1,
"userId": "5e60ec371dc3d30e61c6805b",
"postId": "5e6356546d284c2cdfe1ad92",
"__v": 0,
"likes": []
}
Don't know what I am doing wrong here. Please help.
When everybody said that query is okay and the problem should be in the name of collection. Then I try to get the list of my collections with following code:-
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
//trying to get collection names
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});})
And i was surprised that mongoose changed the name of all the collections to small letters. Collection name commentLikes became commentlikes . Now my query is working good.
If type of _id
field in comments collection is of type ObjectId()
& if commentId
in commentLikes collection is a string then, Try below query :
Comments.aggregate([
{ $match: { postId: postId } },
{
$lookup:
{
from: "commentLikes",
let: { id: { $toString: "$_id" } }, // Convert ObjectId() to string to match with type of commentId(string)
pipeline: [
{
$match:
{
$expr:
{ $eq: ["$$id", "$commentId"] }
}
}
],
as: "likes"
}
}
])
.exec()
Test : MongoDB-Playground
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.