0

I need to populate "contents" on lesson property, but the array return empty.

I'm using the plugin autopopulate and its work fine, but doesnt work with multiple levels. I tried the documentation, but 2 levels I didnt found a solutions.

It's my Schema.

const structure = {
  name: {
    type: String,
    required: true
  },
  lessons: [{
    name: String,
    contents: [{
      type: ObjectId,
      ref: 'Content',
      autopopulate: true
    }]
  }]
}

It's my query to get content.

Course.findById(contentData.course_id)
    .populate({
      path: 'lessons.contents',
      model: 'Content'
    })
    .exec((err, a) => {
      console.log(a);
      res.status(201).json(a)
  });

The array of contents in lessons return empty, but exit two registers on db.

"lessons": [
        {
            "contents": [],
            "name": "Nova Aula"
        }
    ],
Marlos Carmo
  • 972
  • 1
  • 8
  • 13
  • Did you look this one https://stackoverflow.com/questions/19222520/populate-nested-array-in-mongoose.... I hope it helps ! – Code Reactor Mar 10 '19 at 19:04
  • I looked it, but doesnt work to me. Thanks – Marlos Carmo Mar 10 '19 at 19:46
  • @MarlosCarmo Are you fine with using mongodb aggregation pipeline, to achieve the same result? Your query looks fine to me, but i have no idea about `mongoose-autopupulate`. It can be done even without that, with plain mongoose. – Ravi Shankar Bharti Mar 11 '19 at 05:37

1 Answers1

0

Model your Schema like this...

const structure = {
  name: {
    type: String,
    required: true
  },
  lessons: [{
    name: String,
    contents: [{
      type: ObjectId,
      ref: 'Content',
      //remove this line
      //autopopulate: true 
    }]
  }]
}

Your code can look like this...

const result = Course.findById(contentData.course_id)
                     .populate('lessons.contents')
                     .select('_id x y z'); // x,y,z --> attributes name you want to select from populated collection
response.send(result);