0

I have a schema like this for a family (whose children are enrolled in a school)...

var familySchema = new Schema({
    parents: [{
        firstName: String,
        lastName: String,
        email: String,
    }],
    students: [{
        firstName: String,
        lastName: String,
        grade: Number,
    }]
});

I'd like to describe many schools that contain classrooms, and have the classrooms contain students, something like this...

var schoolSchema = new Schema({
    name: String,
    street: String,
    classrooms: [{
        classroomNumber: Number,
        students: [ /* I am mixed up here */ ]
    }]
});

How do I tell mongoose that I want an array of object ids for students found in the other collection?

I understand from this answer that, if I wanted the classrooms to refer to family documents, I could say something like:

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

but how do I do the same for sub-documents of another collection? (If it isn't obvious, I'm just learning both mongo and mongoose).

4

1 回答 1

1

如果要使用子文档引用,则需要更改对'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 );
于 2016-02-17T04:17:02.757 回答