简体   繁体   中英

Mongoose populate nested element inside of multiple arrays

I have the following schema:

const userSchema = new Schema({
    ...,
    categories: [
        {
            name: {
                type: String,
                required: true
            },
            products: [
                {
                    type: mongoose.Types.ObjectId,
                    required: false,
                    ref: 'Product'
                }
            ]
        }
    ],
...
}

I want to get all the products a user have.

I have seen more questions about this topic but I don't get it to work.

If you entered your data correctly you can do like this:

let result = await User.findById(id).populate("categories.products").lean()

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