Search code examples
node.jsmongodbmongoosepopulate

Mongoose: populate an object inside an array


I have a schema exported like that:

const PackageSchema = new Schema({
  name: { type: String, required: true },
  maneuver: [
    {
      maneuverId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: ManeuverMainly,
      },
      period: { type: String, enum: ["day", "night"], required: true },
    },
  ],
  timestamp: { type: Date, default: Date.now() },
});

When I make a find() like that:

Package.find().populate("maneuver", "name").exec((err, data) => {
    if (err) {
      res.status(500).send({ message: "Failed!" });
      return;
    }
    res.status(200).send(data);
});

My populate method does not work. How can I populate my every maneuverId from PackageSchema with my name column from ManeuverMainlySchema?

Obs: my ManeuverMainlySchema bellow:

const ManeuverMainlySchema = new Schema({
  name: { type: String, required: true },
  description: { type: String, required: true },
  timestamp: { type: Date, default: Date().now },
});

Solution

  • taken from Mongoose populate with array of objects containing ref you have to specify the field within the object of the array you want to populate against.

    Package.find().populate("maneuver.maneuverId", "name").exec((err, data) => {
        if (err) {
          res.status(500).send({ message: "Failed!" });
          return;
        }
        res.status(200).send(data);
    });