Skip to content

Commit

Permalink
pre-populate entity virtuals if virtuals population is requested
Browse files Browse the repository at this point in the history
  • Loading branch information
Freezystem committed May 3, 2023
1 parent 7c26f1d commit dfd1e96
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
36 changes: 28 additions & 8 deletions packages/moleculer-db-adapter-mongoose/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,17 +310,37 @@ class MongooseDbAdapter {
* Convert DB entity to JSON object
*
* @param {any} entity
* @param {Context} ctx - moleculer context
* @returns {Object}
* @memberof MongooseDbAdapter
*/
entityToObject(entity) {
let json = entity.toJSON();
if (entity._id && entity._id.toHexString) {
json._id = entity._id.toHexString();
} else if (entity._id && entity._id.toString) {
json._id = entity._id.toString();
}
return json;
entityToObject(entity, ctx) {
const fieldsToPopulate = _.get(ctx, "params.populate", []);
const virtualFields = Object.values(_.get(this, "model.schema.virtuals", {}))
.reduce((acc, virtual) => _.get(virtual, "options.ref") ? [...acc, virtual.path] : acc, []);
const virtualsToPopulate = _.intersection(fieldsToPopulate, virtualFields);
const options = {skipInvalidIds: true, lean: true};
const populate = virtualsToPopulate.map(path => ({path, select: "_id", options}));

return Promise.resolve(populate.length > 0 ? entity.populate(populate) : entity)
.then(entity => {
const json = entity.toJSON();

if (entity._id && entity._id.toHexString) {
json._id = entity._id.toHexString();
} else if (entity._id && entity._id.toString) {
json._id = entity._id.toString();
}

if (virtualsToPopulate.length > 0) {
for(const field of virtualsToPopulate) {
const virtual = json[field];
json[field] = Array.isArray(virtual) ? virtual.map(m => m._id) : virtual._id;
}
}

return json;
});
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/moleculer-db/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ module.exports = {
return Promise.resolve(docs)

// Convert entity to JS object
.then(docs => docs.map(doc => this.adapter.entityToObject(doc)))
.then(docs => Promise.all(docs.map(doc => this.adapter.entityToObject(doc, ctx))))

// Apply idField
.then(docs => docs.map(doc => this.adapter.afterRetrieveTransformID(doc, this.settings.idField)))
Expand Down

0 comments on commit dfd1e96

Please sign in to comment.