如何在猫鼬中通过ObjectId进行引用

时间:2019-07-06 12:25:34

标签: javascript node.js mongodb express mongoose

我不确定如何根据ID列表填充对象。

我正在使用以下架构:

const parentSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    children: Array,
    className: String
)}

const ParentModel = mongoose.model('Parent', parentSchema);

响应将如下所示:

[
  {
    _id: 1,
    children: [2, 3],
    className: 'first',
  },
  {
    _id: 2,
    children: [4],
    className: 'second',
  },
  {
    _id: 3,
    children: [],
    className: 'third',
  },
  {
    _id: 4,
    children: [],
    className: 'forth',
  }
]

我只是想知道是否有可能用children数组中具有id的对象填充children字段。

预期结果:

[
  {
    _id: 1,
    children: [
      {
        _id: 2,
        children: [
          {
            _id: 4,
            children: [],
            className: 'forth',
          }
        ],
        className: 'second',
      },
      {
        _id: 3,
        children: [],
        className: 'third',
      },
    ],
    className: 'first',
  }
]

0 个答案:

没有答案