0

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.

  • Does this answer your question? [How to populate nested entities in mongoose?](https://stackoverflow.com/questions/36996384/how-to-populate-nested-entities-in-mongoose) – Rilla Jan 12 '21 at 22:20
  • if your problem isn't solved with my answer, added controller, because I tested my solution and it's correct – Mohammad Yaser Ahmadi Jan 12 '21 at 22:40

1 Answers1

0

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

let result = await User.findById(id).populate("categories.products").lean()
Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39