Steven
Steven

Reputation: 1173

Mongoose errors on populate

I have two collections which have a relation to each other. One session can contain multiple students, which I want to retrieve via using populate(). These are the schema's:

const studentSchema = new Schema({
    first_name: String,
    last_name: String
}) 

const sessionSchema = new Schema({
    course_code: String,
    students: [{ type: Schema.Types.ObjectId, ref: 'Student' }]
})

const Session = mongoose.model('sessions', sessionSchema)
const Student = mongoose.model('students', studentSchema)

Whenever I use findOne() on session or student it gives the desired output. However when I use populate() like this, it gives me an error:

Session
    .findOne({'course_code': '5072NEAN6Y'})
    .populate("students")
    .exec(function (err, ps){
        if(err){
            console.log(err);
            return;
         }
         console.log("succes");
});

The error: MissingSchemaError: Schema hasn't been registered for model "Student".

Can somebody tell me what I'm doing wrong?

Upvotes: 1

Views: 114

Answers (1)

Steven
Steven

Reputation: 1173

Apparently changing the parameter of populate() made it work:

.populate({path: 'students', model: Student})

Upvotes: 2

Related Questions