小编Roh*_*ore的帖子

从添加到具有层次结构的 mongodb 的类别和子类别中创建 json 对象

我使用节点在 mongoDB 中创建了类别,为每个插入添加了父属性以确定哪个是父类别。

[{ _id: 5889a06f274afdfd6f2bf249,
    cat_id: 1,
    title: 'Parent Category',
    description: '',
    parent: null,
    status: 1}]

[{ _id: 5889a06f274afdfd6f2bf249,
    cat_id: 1,
    title: 'Child Category',
    description: '',
    parent: 1,
    status: 1}]
Run Code Online (Sandbox Code Playgroud)

现在,当我使用 mongoDB 的 db.find() 方法查询时,输出 json 应该使用 node。

{
  obj: [
  { 
    _id: "5889a06f274afdfd6f2bf249",
    cat_id: 1,
    title: "Parent Category",
    description: "",
    parent: null,
    status: 1, 
    subcategories: [
      { 
        _id: "5889a06f274afdfd6f2bf249",
        cat_id: 1,
        title: "Child Category",
        description: "",
        parent: 1,
        status: 1

      }
    ]

  }
]}
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongodb-query aggregation-framework

1
推荐指数
1
解决办法
2321
查看次数