[英]How to join/populate 3 tables with one to many relationships in MongoDB/Mongoose?
我的架构如下所示:
老师.js
const teacherSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
},
},
{
timestamps: true,
}
);
teacherSchema.virtual('students', {
ref: 'Student',
localField: '_id',
foreignField: 'teacher',
justOne: false
})
const Teacher = mongoose.model('Teacher', teacherSchema);
学生.js
const studentSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
teacher: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Teacher',
required: true,
},
},
{
timestamps: true,
}
);
menuItemSchema.virtual('courses', {
ref: 'Course',
localField: '_id',
foreignField: 'student',
justOne: false
})
const Student = mongoose.model('Student', studentSchema);
课程.js
const courseSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
student: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Student',
required: true,
}
},
{
timestamps: true,
}
);
mongoose.model('Course', coursesSchema)
在我的路由器中,我想创建一个如下所示的 object 并将其返回给用户:
{
<teacherName>: [
<studentName1>: [<courseName1>, <courseName2>, <courseName3>],
<studentName2>: [<courseName1>, <courseName2>, <courseName3>]
]
}
要执行此操作,我需要在 3 个表之间进行多重连接。 最有效的方法是什么?
在只有两张桌子的情况下,我会这样做:
const teacherWithStudents = await (await Teacher.findOne({_id: req.params.teacherId}).populate('students')).execPopulate()
但是,由于还有另一张桌子,有没有办法填充学生的课程,以便他们可以访问所有 3 个:老师、她的学生和他们的每个课程。
您可以使用.populate()
更深入地 go,如下所示:
Teacher.findOne({_id: req.params.teacherId})
.populate({
path: 'students',
populate: {
path: 'courses'
}
})
.exec(function(err, docs) {});
更多文档: https://mongoosejs.com/docs/populate.html#deep-populate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.