ReconditusNeumen
ReconditusNeumen

Reputation: 121

Mongoose Populate Virtuals not working and returning null

I read about Mongoose Populate Virtuals and thought that it was cool that it's similar to a join operation in SQL.

When I tried it on my app, it wouldn't work. My app is similar to this, only simplified

I have a Classroom and Teacher Schema in separate files

Classroom.js

...
...
var ClassroomSchema = new Schema({
   class_code:String,
   teacher_id:String
});

ClassroomSchema.virtual('teacher',{
   ref:'Teacher',             //model to reference
   localField:'teacher_id',   //Class.teacher_id
   foreignField:'teacher_id', //a Teacher.teacher_id
   justOne:true
});

module.exports = mongoose.model('Classroom',ClassroomSchema');

Teacher.js

***
***
var TeacherSchema = new Schema({
   name:String,
   teacher_id:String
});

module.exports = mongoose.model('Teacher',TeacherSchema);

in my app.js

var Classroom = require('Classroom.js');
var Teacher = require('Teacher.js');

//Find classrooms
Classroom.find({}).populate('teacher').exec(function(err,docs){
    if(err) throw err
    if(docs) console.log(docs);
});

It would then return classrooms but with the 'teacher' field equal to null

Am I missing something here? Why does it return null?

Upvotes: 2

Views: 3097

Answers (2)

kollors
kollors

Reputation: 1

it didn't work on version after 5.2.18. if set virtuals true you have only virtual fields and if set false you have virtual populate but not fields

Upvotes: 0

rodrigoap
rodrigoap

Reputation: 7480

Add the toJson and toObject options to the Schema like this:

var ClassroomSchema = new Schema({
   class_code:String,
   teacher_id:String
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true }});

Upvotes: 10

Related Questions