【发布时间】:2020-05-30 12:24:07
【问题描述】:
我在 mongodb 中有两个名为“users”和“posts”的集合
用户看起来像这样:-
[
{
"_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 和 Post。
我无法聚合(无法对帖子和用户应用内部联接)
这是我目前正在使用的代码:-
const posts = await Post.aggregate([
{
"$lookup": {
"from": "users",
"localField": "createdBy",
"foreignField": "_id",
"as": "userInfo"
}
}
]).exec()
在结果中,它返回带有空 userInfo 对象的帖子对象数组。 有人可以帮我解决这个问题吗...
【问题讨论】:
-
如果
"createdBy"是一个字符串,您需要将其转换为ObjectId()以匹配_id的用户。那么createdBy的类型是什么? -
_id 是 ObjectId() 并且 createdBy 是字符串。
标签: node.js mongodb mongoose mongodb-query aggregation-framework