我對如何解決這個問題感到困惑。我想用特定的StudyGroup模型來填充我的studyGroups數組中的我的用戶模型。我通過路由器(用戶爲cuid: req.params.cuid
,研究組爲guid: req.params.guid
)獲得特定用戶和studyGroup。Mongoose使用另一個Model對象填充數組字段
這裏是我的代碼如下所示:
用戶
const userSchema = new Schema({
cuid: { type: 'String', required: true },
firstName: { type: 'String', required: true },
lastName: { type: 'String', required: true },
studentId: { type: 'Number', required: true },
password: { type: 'String', required: true },
email: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
lastLogin: { type: 'Date', default: null, required: false },
studyGroups: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "studyGroup"
}
]
});
StudyGroup
const studyGroupSchema = new Schema({
guid: { type: 'String', required: true },
groupName: { type: 'String', required: true },
course: { type: 'String', required: true },
teacher: { type: 'String', required: true },
description: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
});
路線
router.route('/:cuid/studyGroups/:guid').post(UserController.addUserStudyGroups);
這裏是所有動作發生的地方。首先我找到了用戶,現在我想將整個studyGroup模型對象添加到數組中。所以我的想法是使用guid: req.params.guid
查詢studyGroup,但不知道這是否是正確的方法。
控制器
export function addUserStudyGroups(req, res) {
User.findOne({ cuid: req.params.cuid }).populate('studyGroups').exec((err, studyGroups) => {
if (err) {
return res.status(500).send(err);
}
study
return res.json({ studyGroups });
});
}