Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow defining virtuals on arrays, not just array elements #14955

Merged
merged 1 commit into from
Oct 15, 2024

Conversation

vkarpov15
Copy link
Collaborator

@vkarpov15 vkarpov15 commented Oct 11, 2024

Summary

Neat little feature that allows defining virtuals on arrays, so you can define a last virtual on an array that gets you the last element in the array:

schema.virtual('nums.last', { applyToArray: true }).get(function() {
  return this[this.length - 1];
});

// Later
doc.nums.last; // last element in the array

Fix #2326

Examples

@vkarpov15 vkarpov15 added this to the 8.8 milestone Oct 11, 2024
@vkarpov15 vkarpov15 mentioned this pull request Oct 11, 2024
Comment on lines +14011 to +14016
schema.path('books').virtual('last').get(function() {
return this[this.length - 1];
});
schema.virtual('books.first', { applyToArray: true }).get(function() {
return this[0];
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just to make sure, these 2 ways (.path().virtual() & .virtual('path', applyToArray)) are equivalent?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes they are equivalent.

@vkarpov15 vkarpov15 changed the base branch from master to 8.8 October 15, 2024 15:35
@vkarpov15 vkarpov15 merged commit c888efd into 8.8 Oct 15, 2024
63 checks passed
@hasezoey hasezoey deleted the vkarpov15/gh-2326 branch October 16, 2024 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

virtual path on array
2 participants