【发布时间】:2017-02-21 19:56:54
【问题描述】:
我真的很困惑如何解决这个问题。我想用特定的 StudyGroup 模型填充我的 User 模型的 studyGroups 数组。我通过路由器获取特定的用户和 studyGroup(cuid: req.params.cuid 为用户,guid: req.params.guid 为 studyGroup)。
我的代码如下所示:
用户
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"
}
]
});
研究组
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 });
});
}
【问题讨论】: