gpt4 book ai didi

javascript - 来自不同集合的子文档 ID 数组的 Mongoose 模式

转载 作者:行者123 更新时间:2023-12-03 07:40:08 25 4
gpt4 key购买 nike

我有一个像这样的家庭模式(其 child 在学校就读)...

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 我想要在其他集合中找到的学生的对象 ID 数组?

我明白了from this answer如果我希望类里面引用家庭文件,我可以这样说:

families: { type : ObjectId, ref: 'Family' }

但是我如何对另一个集合的文档执行相同的操作? (如果不明显,我只是在学习 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 );

关于javascript - 来自不同集合的子文档 ID 数组的 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com