moleculerjs / moleculer-db

:battery: Database access service mixins for Moleculer
https://moleculer.services/
MIT License
152 stars 123 forks source link

Virtuals with reference are not populated when using mongoose adapter #355

Closed Freezystem closed 1 year ago

Freezystem commented 1 year ago

Using:

Problem:

Virtuals that works with reference to another model are not populated properly due to how transformDocuments works. Mongoose adapter is unable to populate virtuals with internal action call because not populated virtuals are undefined in JSON object. Thus it calls the populate action with an undefined value instead of an id or a list of ids.

Solution:

Mongoose adapter should pre-populate virtuals if they are passed in the ation populate field.
For that matter, we can compare requested populate field list action.params.populate to schema virtuals service.schema.model.schema.virtuals.
Fields that occurs in both should be pre-populated with _id field only.
Then the populate method will be able to operate properly.

I've written acceptance tests for this feature here.

Potential drawbacks:

Population request will be called twice:

It may not be that costly as population request may be internally cached by mongo engine.

I'll try to propose an implementation of it.
Let me know if you have a better idea to solve this issue.

icebob commented 1 year ago

I'm not a mongoose expert, I have no idea which is the best solution. If you have a proposal, start a draft PR and we can see and try it.