2

How to populate ref document in Sub Document, this my schema:

var person = mongoose.Schema({
    name: { type: [String], index: true },
    career: [{
        position: { type: mongoose.Schema.Types.ObjectId, ref: 'Orgchart' }
    }]
};

var orgchart = mongoose.Schema({
        name: { type: [String], index: true },
};

I tried with this part:

person.find({ _id: "12345" }).populate('orgchart').exec(function(err, data){
  res.send(data);
});

I got error Cannot read property 'name' of undefined when i call on jade template with

item.career._orgchart.name
Rampak
  • 115
  • 1
  • 11

2 Answers2

3

You need to pass the dot-notation pathname of the field to populate to the populate call:

person.find({ _id: "12345" }).populate('career.position').exec(function(err, data){
  res.send(data);
});

Not sure why you're trying to access this using _orgchart from Jade as it's the same position field within an element of the career array that will be populated with the referenced orgchart doc.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

Thanks to Mr JohnnyHK

I use:

person.findOne({ _id: req.params.person }).populate('career.position career.grade').exec(function(err, data){
  res.send(data);
});

I used item.position.name in loop data on jade template

Thanks

Rampak
  • 115
  • 1
  • 11