繁体   English   中英

在猫鼬中填充嵌套对象

[英]Populate nested object in mongoose

这是我的猫鼬图式

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。 如何在猫鼬中填充嵌套对象

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM