来自不同集合的 sub-documents 个 ID 数组的 Mongoose 模式
Mongoose schema for array of sub-documents ids from a different collection
我有这样一个家庭的模式(他们 children 在学校就读)...
var familySchema = new Schema({
parents: [{
firstName: String,
lastName: String,
email: String,
}],
students: [{
firstName: String,
lastName: String,
grade: Number,
}]
});
我想描述很多学校都有教室,教室里有学生,像这样……
var schoolSchema = new Schema({
name: String,
street: String,
classrooms: [{
classroomNumber: Number,
students: [ /* I am mixed up here */ ]
}]
});
我如何告诉 mongoose 我想要在其他集合中找到的学生的 object 个 ID 数组?
我理解from this answer,如果我想让教室参考家庭文件,我可以这样说:
families: { type : ObjectId, ref: 'Family' }
但是我如何对另一个集合的 sub-documents 做同样的事情? (如果不是很明显,我只是在学习 mongo 和 mongoose)。
如果您想使用子文档reference,您需要更改对'student'
数组的引用。
var studentSchema = new Schema({
firstName: String,
lastName: String,
grade: Number,
});
var familySchema = new Schema({
parents: [{
firstName: String,
lastName: String,
email: String,
}],
students: [studentSchema]
});
var schoolSchema = new Schema({
name: String,
street: String,
classrooms: [{
classroomNumber: Number,
students: [ { type: ObjectId, ref: 'Family.students' }]
}]
});
var Student = mongoose.model('Student', studentSchema );
var Family = mongoose.model('Family ', familySchema );
var School = mongoose.model('School', schoolSchema );
我有这样一个家庭的模式(他们 children 在学校就读)...
var familySchema = new Schema({
parents: [{
firstName: String,
lastName: String,
email: String,
}],
students: [{
firstName: String,
lastName: String,
grade: Number,
}]
});
我想描述很多学校都有教室,教室里有学生,像这样……
var schoolSchema = new Schema({
name: String,
street: String,
classrooms: [{
classroomNumber: Number,
students: [ /* I am mixed up here */ ]
}]
});
我如何告诉 mongoose 我想要在其他集合中找到的学生的 object 个 ID 数组?
我理解from this answer,如果我想让教室参考家庭文件,我可以这样说:
families: { type : ObjectId, ref: 'Family' }
但是我如何对另一个集合的 sub-documents 做同样的事情? (如果不是很明显,我只是在学习 mongo 和 mongoose)。
如果您想使用子文档reference,您需要更改对'student'
数组的引用。
var studentSchema = new Schema({
firstName: String,
lastName: String,
grade: Number,
});
var familySchema = new Schema({
parents: [{
firstName: String,
lastName: String,
email: String,
}],
students: [studentSchema]
});
var schoolSchema = new Schema({
name: String,
street: String,
classrooms: [{
classroomNumber: Number,
students: [ { type: ObjectId, ref: 'Family.students' }]
}]
});
var Student = mongoose.model('Student', studentSchema );
var Family = mongoose.model('Family ', familySchema );
var School = mongoose.model('School', schoolSchema );