简体   繁体   中英

Mongoose how to populate schema in array

This is my mongodb "profiles"

{
"_id":{"$oid":"5eabd07815cb2679af47701a"},
"user":{"$oid":"5ea54ee9ee3a62a79df1501f"},
"bio":"blah blah",
"date":{"$date":"2020-05-01T07:32:08.583Z"},
"__v":22,
"trainings":
[{
"_id":{"$oid":"5ead9489ab3cd28a0acfadab"},
"training":{"$oid":"5eabcd64c1499375c502b7fe"},
"status":0}
]}

And I could populate "user" with this code:

const profile = await Profile.findOne({
      user: req.user.id,
    })
      .populate("user")

And I get this from profile const:

"_id": "5eabd07815cb2679af47701a",
    "user": {
        "_id": "5ea54ee9ee3a62a79df1501f",
        "username": "blah",
        "email": "blah@gmail.com",
        "avatar": "blah blah",
        "password": "asdasda233123k1j2312l3kOArzuW7iWttO1/n0JDOctybGzdfetNZm",
        "date": "2020-04-26T09:05:45.897Z",
        "__v": 0
    },
    "bio": "blah blah",
    "date": "2020-05-01T07:32:08.583Z",
    "__v": 22,
    "trainings": [
        {
            "_id": "5ead9489ab3cd28a0acfadab",
            "training": "5eabcd64c1499375c502b7fe",
            "status": 0
        }
    ]

The question is, how can i populate "training" in trainings? just like user

Ok, I've done it this way:

const profile = await Profile.findOne({
      user: req.user.id,
    })
      .populate("user")
      .populate("trainings.training");

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