[英]MongoDB - Find all the records from another table
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 .
集合名称commentLikes变成了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 集合中
_id
字段的类型是ObjectId()
类型&如果commentLikes 集合中的commentId
是字符串,则尝试以下查询:
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测试: MongoDB-Playground
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.