NodeJS - 递归填充多个字段

时间:2018-01-25 13:31:43

标签: node.js mongodb recursion mongoose mongodb-query

我得到了这个函数,它以递归方式填充children模型的Page字段。但是我发现自己也必须为modules字段执行此操作,所以我花了最后2个小时尝试重写它,以便它支持填充多个字段,但没有运气。

这是功能:

exports.getSingle = (req, res, next) => {

  Page.findOne({_id: req.params.pageId})
    .exec((err, page) => {

    if (err || !page) {
      return next(err || 'No page with that _id');
    }

    const populate = (coll, id) => {

      return coll.findOne({_id: id})
        .then((page) => {

          if (!page.children || !page.children.length) {
            return page;
          }

          return Promise.all(page.children.map(childId => populate(coll, childId)))
            .then(children => Object.assign(page, {children}))
        });
    }

    populate(Page, page._id).then((page) => {

      res.json({
        error: null,
        data: page
      });
    });
  });
};

我尝试的是向名为field的函数添加新参数,并将所有children次出现更改为field。在Promise.all中添加新映射时,我最终会得到奇怪的错误和未填充的数据。

如何实现填充多个字段?

修改

以下是Page模型:

const PageSchema = new Schema({
  appConfigId: {type: mongoose.Schema.Types.ObjectId, ref: 'AppConfig'},
  parent: {type: mongoose.Schema.Types.ObjectId, ref: 'Page', default: null},
  children: [{type: mongoose.Schema.Types.ObjectId, ref: 'Page'}],
  modules: [{type: mongoose.Schema.Types.ObjectId, ref: 'Module'}],
  settings: {
    label: {type: String, default: '', maxlength: 100, required: true},
    url: {type: String, default: ''},
    data: {}
  },
  metadata: {
    type: {type: String, default: 'page', required: true}
  }
});

const Page = mongoose.model('Page', PageSchema);

这是Module模型:

const ModuleSchema = new Schema({
  label: {type: String, required: true},
  modules: [{type: mongoose.Schema.Types.ObjectId, ref: 'Module'}],
  settings: {type: mongoose.Schema.Types.Mixed, default: {}},
  metadata: {
    type: {type: String, required: true},
    component: {type: String, required: true}
  }
});

const Module = mongoose.model('Module', ModuleSchema);

0 个答案:

没有答案