Итак, у меня есть 3 модели в MongoDB, из которых я пытаюсь получить определенное поведение и немного борюсь с этим.
У меня есть его, так что я могу добавлять или удалять студентов на курсы, и он будет обновлять массивы на обоих концах. Аналогично для добавления и удаления курсов.
Что я пытаюсь сделать сейчас, это запросить все в массиве courseIds и вернуть набор всех студентов по всем курсам, которые принадлежат учителю.
Я потратил приличную часть времени, пытаясь получить это, но информация об этом кажется скудной, так как они не очень хорошо работают с населением.
Мои модели сейчас выглядят так:
const StudentSchema = new Schema({
name: {
type: String,
required: true,
index: true
},
age: {
type: Number,
required: true
},
grade: {
type: Number,
required: true
},
notes: {
type: String
},
courseIds: [
{
type: Schema.Types.ObjectId,
ref: "Course"
}
]
});
const CourseSchema = new Schema({
subject: {
type: String,
required: true
},
year: {
type: String,
required: true
},
term: {
type: String,
required: true
},
period: {
type: String,
required: true
},
grade: {
type: Number,
required: true
},
teacherId: {
type: Schema.Types.ObjectId,
ref: "Teacher"
},
studentIds: [
{
type: Schema.Types.ObjectId,
ref: "Student"
}
]
});
const TeacherSchema = new Schema({
name: {
type: String,
required: true,
index: true
},
email: {
type: String,
required: true,
index: true
},
courseIds: [
{
type: Schema.Types.ObjectId,
ref: "Course"
// autopopulate: true
}
]
});
Я использую экспресс, и мой запрос выглядит так:
router.get("/", (req, res) => {
Teacher.findById(req.body.teacher._id)
.populate({
path: "courseIds",
select: ["subject", "year", "term", "period", "grade", "teacherId"]
})
.exec((err, teacher) => {
console.log(teacher);
let payload = {
teachers: {
[teacher._id]: {
_id: teacher._id,
name: teacher.name,
email: teacher.email
}
},
courses: indexPayload(teacher.courseIds)
};
res.json(payload);
});
});
Текущий ответ выглядит следующим образом. Это очень намеренно, так как я планирую подключить это к циклу реакции / избыточности и хочу использовать шаблон сущностей.
Есть ли способ сделать это в одном запросе или я собираюсь запросить каждый отдельный курс и вернуть набор?
{
"teachers": {
"5d904a0da0383e1cd80cd095": {
"_id": "5d904a0da0383e1cd80cd095",
"name": "Teacher Name",
"email": "teacher.name@awesomeschool.com"
}
},
"courses": {
"5d904a3126b2641d5223be6c": {
"_id": "5d904a3126b2641d5223be6c",
"subject": "Physics",
"year": "2018",
"term": "Spring",
"period": "1",
"grade": 3,
"teacherId": "5d904a0da0383e1cd80cd095"
},
"5d904a3326b2641d5223be6e": {
"_id": "5d904a3326b2641d5223be6e",
"subject": "Physics",
"year": "2018",
"term": "Spring",
"period": "1",
"grade": 3,
"teacherId": "5d904a0da0383e1cd80cd095"
}
}
}