Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

Is it possible to populate a field in mongoose which has other information on it too?


This is the relevant portion of my Schema:

var classroomSchema = mongoose.Schema({
    students: [{
        _id: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        rate: {
            type: Number,
            default: 200,
        },
        referrals: [mongoose.Schema.Types.ObjectId],
    }],
)};

Here rate and referrals are properties of the students which are valid in the context of that classroom, and cannot be populated from the Students model.

Is there any way to define my schema such that I can keep those fields(rate and referrals) and also use populate to link other fields such as name, age, etc of the student?


Solution

  • Change your schema to this:

    var classroomSchema = mongoose.Schema({
        students: [{
            rate: { type: Number, default: 200 },
    
            user: { ref: 'User', type: Schema.Types.ObjectId },
            referrals: [mongoose.Schema.Types.ObjectId],
        }],
    });
    

    Usage:

    classroom
      .findOne(...)
      .populate('user')
      .exec((err, classroom) => {
        let student0 = classroom.students[0];
        // student0.rate
        // student0.user.name
      });