【问题标题】:Mongoose schema for array of sub-documents ids from a different collection来自不同集合的子文档 ID 数组的猫鼬模式
【发布时间】:2016-05-28 14:58:19
【问题描述】:

我有一个这样的架构,适用于一个家庭(其孩子就读于学校)......

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' }

但是我如何对另一个集合的 sub-documents 执行相同的操作? (如果不是很明显,我只是在学习 mongo 和 mongoose)。

【问题讨论】:

    标签: javascript mongodb mongoose mongoose-schema


    【解决方案1】:

    如果要使用子文档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 );
    

    【讨论】:

    • 很好的答案。非常感谢。
    • 嘿 - 很抱歉打扰后续工作:我遵循一种模式,每个模型都有一个文件,每个模型文件最后都显示 module.exports = mongoose.model('Model', ModelSchema);。那么,在我的 family.js 中,我可以在 student 上调用 mongoose.model('Student'... 并丢弃结果(这样我仍然可以导出家庭模型)吗?而且,在我的 school.js 中,我是否必须要求任何其他模型文件才能使用您建议的语法?
    • @user1272965,在每个模型文件中,你可以使用mongoose.model('Model', ModelSchema);,当你想在其他文件中使用这个模型文件时,你应该使用var School = mongoose.model('School');,然后这个School可以使用在这个文件中......希望我清楚自己。
    • 使用上述方法,当我在 find 中使用 populate() 时 - 它返回错误,因为“架构尚未为模型“Family.students”注册”
    猜你喜欢
    • 2016-01-27
    • 2019-08-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2021-07-22
    • 2020-11-18
    • 2020-03-27
    • 2018-05-17
    相关资源
    最近更新 更多