Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.88k stars 3.83k forks source link

Model.applyVirtuals(): apply schema virtuals to a POJO, similar to Model.applyDefaults() #14818

Open Vladyslav531 opened 3 weeks ago

Vladyslav531 commented 3 weeks ago

Prerequisites

🚀 Feature Proposal

Supporting virtual fields in aggregate will be good feature.

I know aggregate is server-side feature and virtual fields is client-side feature and aggregation results can change shape of document. However, some aggregate results just extends document data and it is possible to add virtual fields to aggregate results, just I mentioned in motivation. I think we can add hasVirtualFields to aggregate options which default is false and add virtual fields to aggregate results.

Motivation

I am using aggregate function for pagination. Since aggregate doesn't support virtual fields, I need to hydrate each aggregation result and add virtual fields to each aggregation result manually. It will be good to do in mongoose itself.

Example

UserModel.aggregate([
  // add pipelines
], {
  hasVirtualFields: true
});

So, we can add virtual fields like fullName to aggregate results.

windward-hive commented 3 weeks ago

"Virtuals are properties on Mongoose documents. If you use the lean option, that means your queries return POJOs rather than full Mongoose documents. That means no virtuals if you use lean()." Aggregate returns POJO, just like lean. Since virtuals are tied to mongoose documents, they won't work with aggregation results.

Vladyslav531 commented 3 weeks ago

I understand totally. However, we can use hydrate to convert POJO to mongoose document and so, it is possible to add virtual fields to aggregation result.

vkarpov15 commented 3 weeks ago

I think adding a Model.applyVirtuals() function similar to Model.applyDefaults() would be helpful. That way you can pass in an arbitrary object and have Mongoose apply the schema's virtuals to that object. @Vladyslav531 does that sound like it would fix your issue?

Vladyslav531 commented 3 weeks ago

Yes, that sounds great, @vkarpov15