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).

Community
  • 1
  • 1
user1272965
  • 2,814
  • 8
  • 29
  • 49

1 Answers1

1

If you want to use sub-documents reference, you need to change your reference to the 'student' array.

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 );
zangw
  • 43,869
  • 19
  • 177
  • 214
  • Great answer. Thanks very much. – user1272965 Feb 17 '16 at 15:22
  • Hey - sorry to bother with a followup: I'm following a pattern where I have one file per model, and each model file says `module.exports = mongoose.model('Model', ModelSchema);` at the end. So, in my family.js, can I just call `mongoose.model('Student'...` on student and discard the result (so I can still export the family model)? And, in my school.js, must I require any other model files to use the syntax you suggest? – user1272965 Feb 17 '16 at 15:44
  • @user1272965, in each model file, you can use `mongoose.model('Model', ModelSchema);`, when you want to use this model file in other file, you should use `var School = mongoose.model('School');`, then this `School` could be use in this file... Hope I make myself clearly. – zangw Feb 18 '16 at 01:53
  • Using above method, when i use populate() in find - it returns error as 'Schema hasn't registered for model "Family.students"' – user3211705 Nov 15 '16 at 18:59