我正在尝试使用Mongoose在用户之间建立多对多的关系。
有两种类型的用户:教师和学生。教师可以负责任意数量的学生。另一方面,学生可以对应多个教师。
我创建了一个模式关系,它有两个条目,老师和学生,引用用户模式中的ObjectId。
var RelationSchema = new Schema({
teacher: {
type: Schema.Types.ObjectId,
ref: 'User'
},
student: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
向所有学生询问一位老师的负责人是微不足道的。 ----(1)
在查询补充集时,它变得不那么明显了。第一个想法是查询所有用户减去(1)的结果。
User.find({}, function(err, users) {
if (err) { /*handle and return */ }
Relation.find({teacher: teacherId})
.populate({path: 'student'})
.exec(function(err, relations) {
if (err) { /* handle and return */ }
// map relations to students
var students = _.map(relations, function(relation) {
return relation.student;
});
});
// Return the difference of users and students
// i.e., complement = users - students
});
但是,上述方法可能会导致巨大的开销。 查询一位老师负责的学生补充集的最有效方法是什么?