【问题标题】:Populate nested object in mongoose在猫鼬中填充嵌套对象
【发布时间】:2019-02-10 07:45:37
【问题描述】:

这是我的猫鼬模式

const bookModel = new schema({
  bookInfo: {
    bookedUser: {
      id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "UserInfo"
      },
      username: String
    },
    date: String,
    machineryName: String,
    phoneNo: String,
    address: String,
    Acre: String,
    decision: Boolean,
    acceptedDriver: {
      id: { type: mongoose.Schema.Types.ObjectId, ref: "DriverInfo" },
      username: String
    }
  }
});

module.exports = mongoose.model("bookInfo", bookModel);

填充包含多个 id 的 bookInfo 数组后的输出

{
    "bookInfo": [
        {
            "bookInfo": {
                "bookedUser": {
                    "id": "5c5e70847921dd3b0c2eb047",
                    "username": "UR"
                },
                "acceptedDriver": {
                    "id": "5c5e6f7896f2f6386c717749",
                    "username": "DR"
                },
                "date": "12",
                "address": "jjkjkljlj",
                "Acre": "2",
                "decision": true
            },
            "_id": "5c5e70ad7921dd3b0c2eb048",
            "__v": 0
        }
]
}


My query 
router.get("/requests", async (req, res) => {
  const requests = await User.findById(req.user._id)
    .populate("bookInfo")
    .populate("bookInfo.bookInfo.bookedUser.id")
    .exec();
  res.json(requests);
});

此代码填充到 bookInfo,但我希望填充包含 id 字段的 bookInfo。如何在 mongoose 中填充嵌套对象

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    试试这个

    router.get("/requests", async (req, res) => {
      const requests = await User.findById(req.user._id)
        .populate(path:"bookInfo", populate:{path:"bookInfo.bookedUser.id"})
        .exec();
      res.json(requests);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 2016-08-17
      • 2018-10-15
      • 1970-01-01
      • 2021-12-25
      • 2015-11-24
      • 2015-02-09
      • 2021-11-07
      • 2020-08-09
      相关资源
      最近更新 更多