猫鼬:填充数组内的对象

Mongoose: populate an object inside an array

我有一个这样导出的模式:

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

当我这样 find() 时:

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

我的populate方法不起作用。 如何使用 ManeuverMainlySchema 中的 name 列填充 PackageSchema 中的每个 maneuverId

Obs:我的 ManeuverMainlySchema 如下:

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

摘自 Mongoose populate with array of objects containing ref 您必须在要填充的数组对象中指定字段。

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