【问题标题】:How to populate without a ref in mongoose model?如何在没有 ref 的情况下填充猫鼬模型?
【发布时间】:2022-02-22 01:16:10
【问题描述】:

问题,我正在尝试填充没有 ref 的模型。原因是我要保存的 objectId 来自两个不同的模型。我的计划是在我的控制器中,我将填充两个模型,我将包含一个 if 语句,说明应该在前端部分传递哪个值。

型号

const sampleSchema= mongoose.Schema({
creatorId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'accountModel',
  },
  whoCanEdit: {
    type: String,
    required: [true, 'Please provide who can edit the project'],
  },
  whoCanEditId: {
    type: mongoose.Schema.Types.ObjectId,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

控制器

export const getProjectById = async (req, res) => {
  try {
    const project = await sampleModel
      .findById(req.params.id)
      .populate('creatorId');

    if (project.whoCanEdit === 'Specific') {
      <---this where I'm planning to populate
    }

    res.status(200).json(project);
  } catch (error) {
    res.status(500).json({ msg: error.message });
  }
};

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    你可以使用Dynamic References

    将另一个字段添加到您的架构并存储模型名称以供填充

    whoCanEditId: {
        type: mongoose.Schema.Types.ObjectId,
        refPath: 'editType'
    },
    editType: {
        type: String,
        required: true,
    }
    

    如果whoCanEdit 是模型的名称,您可以使用它而不是添加editType

    然后像以前一样简单地使用它

    .populate('whoCanEditId')
    

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 2021-06-29
      • 2020-09-13
      • 2019-12-27
      • 2020-07-25
      • 2019-12-31
      • 2020-11-19
      • 2016-04-25
      • 2021-05-16
      相关资源
      最近更新 更多