この問題にどう対処するかは本当に混乱しています。私はユーザーモデルのstudyGroups配列に特定のStudyGroupモデルを設定したいと思います。特定のユーザーとstudyGroupをルータ経由で取得します(cuid: req.params.cuid
、studygroupはguid: req.params.guid
)。ここで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を照会することでしたが、それが正しい方法であるかどうかわかりません。あなたは今$lookup
$lookup
を使用してモンゴ3.2でそれを行うことができます
コントローラ
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 });
});
}