通过expressjs中的mongoose在mongodb中进行聚合

问题描述 投票:0回答:1

我设计了一个数据库,其中有一个名为类别的模型。在此模型中,每个类别本身都有一个 id 和一个父属性,该属性显示该类别是否在另一个分支下(例如,nodejs 是 Web 开发类别的子级)。我想以一种可以显示父母以及将其 id 作为父母的类别的方式来迭代它。 这是父文档的示例:

{
  "title": "web development",
  "_id": "64f04d6b81e4439030ed6073"
  "__v": 0
}

这是子文档的示例:

{
  "title": "nodejs",
  "parent": "the id of web development"
  "__v": 0
}

当我只想获取父母时,我希望我的输出看起来像这样:

    [
 {
     "_id" : "64f04d6b81e4439030ed6073",
     title:"web development",
     children : [the categories that have the mentioned id in parent property]
 },
    other parents....
    ]

我想返回对象数组中的每个父对象,并且每个对象都有一个 Children 属性,其中包括指定该父对象的其他类别。 我非常感谢您提供的任何帮助或提示。

node.js mongodb express mongoose aggregate
1个回答
0
投票

据我了解,您想要的是将所有孩子都交给各自的父母!

如果要实现,可以将外键存储在子表中作为父表的引用。

const blogSchema = new mongoose.Schema(

    {
        name: String,
        description: String,
        userId:
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'user',
        },
        image: {
            type: String,
            required: [true, 'image cannot be null'],
        }
    },


)

这个模型来自我目前正在开发的博客应用程序!

您看到我在这里所做的是将用户 ID 存储为我的博客表中的参考。

现在我怎样才能将所有博客发送给各个用户???或者在您的情况下,各个父母的孩子,这是示例查询。

  const blogs = await blogModel.find({
  userId: user.id
   })

希望这对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.