问题描述
我想定义学生模型和编队模型之间的一对多关系:1个学生属于1个编队,一个编队可以由N个学生组成.
I want to define a one-to-many relationship between my Student model and my Formation model: 1 student belongs to 1 formation and a formation can be composed of N students.
我的需求是:
- 能够使用其学生填充编队"文档
- 轻松检索学生的构成
所以我写道:
let student = new Schema({
firstName: {
type: String
},
lastName: {
type: String
},
formation : {
type: Schema.Types.ObjectId,
ref: 'Formation'
}
});
let formation = new Schema({
title: {
type: String
},
students: [{ type: Schema.Types.ObjectId, ref: 'Student' }]
}
当我搜索有关与mongodb/mongoose一对多关系的文档时,我很惊讶地看到,当我想创建一个Student文档(并将其添加到队形中)时,我一定不会仅将其"formation"字段设置为formation id,并将其推送到formation文档的"students"字段.
是否意味着当我想用另一个班级替换学生的班级时,我将需要1/更新其班级字段2/将自己的学生ID从班级学生"字段中删除,然后将其重新添加到学生领域的新形成?
对我来说似乎有点多余.我想念什么吗?
When I'm searching for documentation about the one-to-many relation with mongodb/mongoose, I'm surprised to see that when I want to create a Student document (and add it to a formation), I must not only set its "formation" field with the formation id and also push it to the formation document "students" field.
Does it imply that when I want to replace the formation of a student with another formation, I'll need to 1/ update its formation field 2/ remove myself the student id from the formation "students" field and re-add it to the students field of the new formation?
It seems a little redundant to me. Am I missing something?
推荐答案
在队形模型上使用students
既不好,也是多余的.潜在的无限数组设计不佳,因为它们可能导致达到文档大小限制.关于冗余,在这种情况下,您只有两个查询:
Having students
on the Formation model is both bad practice and redundant. Potentially infinite arrays are a poor design as they can lead to hitting document size limits. In regards to being redundant, you only have two queries in this situation:
1)您的内存中有一个student
,并且您想查找其形成:
1) You have a student
in memory, and you want to find their formation:
Formation.findOne({_id: student.formation},callback);
2)您的记忆中有一个formation
,并希望找到该编队的所有学生:
2) You have a formation
in memory, and want to find all students in that formation:
Student.find({formation: formation._id}, callback);
两者都不需要在队形架构上具有students
.
Neither of which require having students
on the Formation schema.
这篇关于与猫鼬一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!