1

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 },
});

2 Answers2

0

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);
});
Johannes Merz
  • 3,252
  • 17
  • 33
0
Package.find().populate(["maneuver.maneuverId", "name"]).exec((err, data) => {
    if (err) {
      res.status(500).send({ message: "Failed!" });
      return;
    }
    res.status(200).send(data);
});

If you want to populate one of them, don't need to use array in populate as populate("maneuver.maneuverId") or populate("name").

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Onur Doğan
  • 346
  • 2
  • 8