Search code examples
node.jsmongodbmongoosepopulatesubdocument

Mongoose Populate not working in array of sub-document with "path" option


Here's my Mongoose schema:

const productSchema = mongoose.Schema({
  writer: {
        type: Schema.Types.ObjectId,
        ref: 'User'
  },
  schedule: [{
            dateTime: {
                type: String,
                unique: 1            
            },
            candidates: [{
                type: Schema.Types.ObjectId,
                ref: 'User'
            }],
            attorn: {
                type: Schema.Types.ObjectId,
                ref: 'User'
            }
        }]
   ...

This is where I get my items along with the candidates:

    Product.find({ '_id': { $in: productIds } })
    .populate('writer')
    .populate({ 
        path: 'schedule',
        populate: {
          path: 'candidates',
          model: 'User'
        } 
     })
    .exec((err, product) => {
        if (err) return res.status(400).send(err)
        return res.status(200).send(product)
    })
  1. Result of this code is a product with only populated 'writer' and empty array for 'candidates'
  2. If I remove the line for populating 'candidates', it returns array of _id for 'candidates'
  3. How do I populate the 'candidates' array?

Solution

  • can you try this

    Product.find({ _id: { $in: productIds } })
      .populate("writer")
      .populate({
        path: "schedule.candidates",
      })
      .populate({
        path: "schedule.attorn",
      })
      .exec((err, product) => {
        if (err) return res.status(400).send(err);
        return res.status(200).send(product);
      });