业务背景有一个老师表teacher一个学生表student一个老师关联多个学生现在要查询老师的信息,以及所有学生的信息我的代码// 老师表const teacherSchema = new mongoose.Schema({
name: { type: String },
students: [{ type: mongoose.Schema.Types.ObjectId, ref: 'student' }],
});// 学生表const studentSchema = new mongoose.Schema({
name: { type: String },
teacher: { type: mongoose.Schema.Types.ObjectId, ref: 'teacher' },
});const Teacher = mongoose.model('teacher', teacherSchema);const Student = mongoose.model('student', studentSchema);
(async function test() { // 新增一个老师
const t = await Teacher.create({ name: '张老师' }); // 新增一个学生
const s = await Student.create({
name: '李四',
teacher: t._id,
}); // 将学生关联到老师
t.students.push(s); await t.save(); // 查询老师信息
const teachers = await Teacher.find().populate('students'); console.log(teachers);
}());输入结果[
{ students: [ [Object] ],
_id: 5c69e591510ea44574287fea,
name: '张老师',
__v: 1 } ]问题如果一个老师对应一千个学生,难道要把1000个学生给push到老师的students属性里?这也太夸张了吧?
- 2 回答
- 0 关注
- 1193 浏览
添加回答
举报
0/150
提交
取消