Fork me on GitHub

mongodb 分类自动递归整合

分类关系:每个文档挂载它的父级id。输出时,展示父级所有的子项。

以下是我写的完整案例代码,可运行:
index.js

const mongoose = require('mongoose');
const fs = require('fs')
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
const Menu = mongoose.model('Menu', new mongoose.Schema({
  name: {
    unique: true,
    type: String,
    required: true
  },
  pid: {
    display: '父节点',
    default: 0,
    type: mongoose.Schema.Types.Mixed
  },
}), 'test_menu');

(async function () {
  await Menu.remove({})
  const fa = await new Menu({name: '肉类'}).save()
  await new Menu({name: '猪肉', pid: fa._id}).save()
  await new Menu({name: '羊肉', pid: fa._id}).save()
  const res = await Menu.aggregate([
    {
      $graphLookup: {
        from: "test_menu",
        startWith: "$_id",
        connectFromField: "_id",
        connectToField: "pid",
        as: "children"
      }
    }
  ])
  fs.writeFileSync('./res.json', JSON.stringify(res))
  mongoose.disconnect()
}())

输出结果

[
  {
    "_id": "5dcbbe3835605a17a0bb85c2",
    "pid": 0,
    "name": "肉类",
    "__v": 0,
    "children": [
      {
        "_id": "5dcbbe3935605a17a0bb85c3",
        "pid": "5dcbbe3835605a17a0bb85c2",
        "name": "猪肉",
        "__v": 0
      },
      {
        "_id": "5dcbbe3935605a17a0bb85c4",
        "pid": "5dcbbe3835605a17a0bb85c2",
        "name": "羊肉",
        "__v": 0
      }
    ]
  },
  {
    "_id": "5dcbbe3935605a17a0bb85c3",
    "pid": "5dcbbe3835605a17a0bb85c2",
    "name": "猪肉",
    "__v": 0,
    "children": []
  },
  {
    "_id": "5dcbbe3935605a17a0bb85c4",
    "pid": "5dcbbe3835605a17a0bb85c2",
    "name": "羊肉",
    "__v": 0,
    "children": []
  }
]

api参考: graphLookup