mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Not populating subdocuments of an embedded array #46

Closed bam-tbf closed 5 years ago

bam-tbf commented 6 years ago

Hi. In my User schema I have an embedded array of schema type UserPermission. Even though the autopopulate option is set on some paths inside of UserPermission they are not being autopopulated when the User document is loaded. Both User and UserPermission have the autopopulate plugin enabled. Other autopopulated fields are populating as expected.

I suspect this is because the array is an embedded array, rather than array of refs that need to be populated, correct?

In the short term, what is the easiest way to manually trigger autopopulation of the embedded array after User is loaded?

In the medium/long term, shouldn't this situation be handled by the plugin?

Thank you.

vkarpov15 commented 6 years ago

Can you please clarify your issue with some code samples? Translating prose to code is error prone.

ghmendonca commented 5 years ago

This is not working at all.

Supose that you have the models A and B. In the A model, you define an array of B.

let ASchema = new Schema({ arrayB: { type: [B], autopopulate: true } })

And inside B, you put your relation to another model (let's call model C).

let BSchema = new Schema({ arrayC: { type: [{type: mongoose.Schema.Types.ObjectId, ref: "C"}], autopopulate: true } })

Now if you do A.find(), it will not return the arrayC populated, it will return only an array of object ids..

vkarpov15 commented 5 years ago

Do this instead:

let BSchema = new Schema({ arrayC: { type: [{type: mongoose.Schema.Types.ObjectId, ref: "C", autopopulate: true }] } })