gpt4 book ai didi

node.js - 无法在 Nodejs 的 mongoose 中使用聚合

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:14 24 4
gpt4 key购买 nike

我在 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 应用程序中有两个 Mongoose 模型,分别名为 User 和 Post。

我无法聚合(无法对帖子和用户应用内部联接)

这是我当前正在使用的代码:-

const posts = await Post.aggregate([
{
"$lookup": {
"from": "users",
"localField": "createdBy",
"foreignField": "_id",
"as": "userInfo"
}
}
]).exec()

在结果中,它返回带有空 userInfo 对象的帖子对象数组。有人可以帮我解决这个问题吗...

最佳答案

由于 createdBy 是一个字符串,而 _id 的类型是 ObjectId(),那么您需要将两个字段设置为相同的类型,请尝试以下操作:

Post.aggregate([
{
$lookup:
{
from: "users",
let: { createdBy: "$createdBy" },
pipeline: [
{
$match:
{
$expr:
{ $eq: [{ $toObjectId: "$$createdBy" }, "$_id"] }
}
}
],
as: "userInfo"
}
}
])

测试: MongoDB-Playground

注意:或者,如果您不想每次需要将 createdBy 存储为 ObjectId() 时都进行转换。

因此,在您的 Post 模型中,createdBy 类型应为 Schema.Types.ObjectId

保存Post文档时createdBy:mongoose.Types.ObjectId('someString');

关于node.js - 无法在 Nodejs 的 mongoose 中使用聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60230792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com