我在mongodb中有两个集合,分别是“用户”和“帖子”
用户如下所示:-
[
{
"_id": "5e3ffba65bad3a38dc0509cd",
"name": "Ekansh Jain",
"email": "ejekanshjain@gmail.com",
"password": "$2a$10$lF1evuJgfC0N7fIC4I7KrOG.lq56aiHzndIYwc/YRb3auLTgHfmGK",
"createdAt": "2020-02-09T12:31:34.117Z",
"updatedAt": "2020-02-09T12:31:34.117Z",
"__v": 0
},
{
"_id": "5e403dcd1000793694bd2276",
"name": "Ekansh Jain",
"email": "ejekanshjain2@gmail.com",
"password": "$2a$10$qGmng4KrXVXKt0RLnSMgMueo.BenKM43QIpURrzxW4M.HGDHe//TC",
"createdAt": "2020-02-09T17:13:49.508Z",
"updatedAt": "2020-02-09T17:13:49.508Z",
"__v": 0
}
]
帖子看起来像这样
[
{
"_id": "5e403aa22a28e430b0d2641a",
"title": "My Post 1",
"body": "this is my first post's body",
"createdBy": "5e3ffba65bad3a38dc0509cd",
"createdAt": "2020-02-09T17:00:18.991Z",
"updatedAt": "2020-02-09T17:00:18.991Z",
"__v": 0,
"userInfo": []
},
{
"_id": "5e403e8b1000793694bd2278",
"title": "LOL",
"body": "LOL",
"createdBy": "5e403dcd1000793694bd2276",
"createdAt": "2020-02-09T17:16:59.513Z",
"updatedAt": "2020-02-09T17:16:59.513Z",
"__v": 0,
"userInfo": []
},
{
"_id": "5e46c8cfe56d4325b4e8d334",
"title": "test Post",
"body": "this is my first post's body",
"createdBy": "5e3ffba65bad3a38dc0509cd",
"createdAt": "2020-02-14T16:20:31.771Z",
"updatedAt": "2020-02-14T16:20:31.771Z",
"__v": 0,
"userInfo": []
}
]
我的nodejs Express应用程序中有两个猫鼬模型,分别名为User and Post。
我无法汇总(无法在帖子和用户上应用内部联接)
这是我当前正在使用的代码:-
const posts = await Post.aggregate([
{
"$lookup": {
"from": "users",
"localField": "createdBy",
"foreignField": "_id",
"as": "userInfo"
}
}
]).exec()
结果是,它返回带有空userInfo对象的帖子对象数组。 有人可以帮我这个忙吗?
答案 0 :(得分:0)
由于createdBy
是字符串,而_id
的类型是ObjectId()
,那么您需要将两个字段都设为相同的类型,试试这个:
Post.aggregate([
{
$lookup:
{
from: "users",
let: { createdBy: "$createdBy" },
pipeline: [
{
$match:
{
$expr:
{ $eq: [{ $toObjectId: "$$createdBy" }, "$_id"] }
}
}
],
as: "userInfo"
}
}
])
注意:或者,如果您不想每次将createdBy
存储为ObjectId()
时都进行转换。
因此,在您的Post
模型createdBy
中,类型应该为Schema.Types.ObjectId
。
在保存发布文档createdBy : mongoose.Types.ObjectId('someString');