[英]Many to many relation in mongoDB
我的 nosql 数据库(mongoDB 和 mongoose.js)中有两个模型: User和Class 。
每个 class 有一名教师和多名学生(教师和学生是用户模型)。
每个用户可以有很多类。
实现数据库的最佳解决方案是什么?
我认为在Class model 中包含user_id
数组和在用户class_id
中包含 class_id 数组是最好的,对吗?
假设教师用户不能作为学生,学生用户也不能作为教师。
您可以在架构中使用 mongoose 的ref
(请参阅 文档)。 例如:
const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
// other properties you want to define
classes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Class"
}
]
})
const ClassSchema = new mongoose.Schema({
className: String,
// other properties you want to define
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
]
})
稍后在查询数据库时,您可以使用 mongoose 的填充来自动获取引用的文档,而不仅仅是文档的 id:
User.findById(userId).populate("classes");
Class.findById(classId).populate("users");
这是一个很好的教程,它更详细地解释了它: https://bezkoder.com/mongodb-many-to-many-mongoose/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.