我对如何解决这个问题感到困惑。我想用特定的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 });
});
}