Techuba
Techuba

Reputation: 3

Mongoose: issues populating an object in an array

I have the following three models:

var User = {
first_name: String,
last_name: String,
}

var Student = {
role = String,
user = {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
groups = [{type: mongoose.Schema.Types.ObjectId, ref: 'Group'}],
}

var Group = {
name = String,
students = [{type: mongoose.Schema.Types.ObjectId, ref: 'Student'}],
}

My express get method looks like:

router.route('/')
  .get(function(req, res){
    Group.find().populate('students').exec(function(err, groups){
      res.json(groups);
    });

My json object returns the array of student objects a that are populated, but i am only receiving a user._id from within each of the student objects. How can I also get the user object to populate? Any info would be awesome! Thanks

Upvotes: 0

Views: 252

Answers (1)

gnerkus
gnerkus

Reputation: 12037

You can populate across multiple levels:

router.route('/')
  .get(function(req, res){
    Group
      .find()
      .populate({
        path: 'students',
        // Get the student's user ids
        populate: { path: 'user' }
      })
      .exec(function(err, groups){
        res.json(groups);
      });

You can read more about it here

Upvotes: 1

Related Questions