Mongoose:在数组中填充对象

hrysbysz  于 11个月前  发布在  Go
关注(0)|答案(2)|浏览(117)

我有一个这样导出的schema:

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:my ManeuverMainlySchema bellow:

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

vulvrdjw

vulvrdjw1#

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

字符串

niwlg2el

niwlg2el2#

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

    res.status(200).send(data);
});

字符串
如果你想populate只有一个这样的:populate("maneuver.maneuverId")populate("name")

相关问题