来自不同集合

时间:2016-02-17 04:00:17

标签: javascript mongodb mongoose mongoose-schema

我为一个家庭(他们的孩子在学校注册)有这样的架构...

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 - 文档执行相同的操作? (如果不是很明显,我只是学习mongo和mongoose)。

1 个答案:

答案 0 :(得分: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 );