简体   繁体   中英

Populate nested object in mongoose

here is my mongoose schema

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

output after populating bookInfo array which contains multiple ids

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

this code populates till bookInfo but i want the bookInfo including the id field to be populated . how to populate nested objects in mongoose

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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