【发布时间】: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 });
}
};
【问题讨论】: