Skip to content

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

Merged
vkarpov15 merged 1 commit into8.8from
vkarpov15/gh-2326
Oct 15, 2024
Merged

feat: allow defining virtuals on arrays, not just array elements#14955
vkarpov15 merged 1 commit into8.8from
vkarpov15/gh-2326

Conversation

@vkarpov15
Copy link
Copy Markdown
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 thread test/document.test.js
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
Copy Markdown
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
Copy Markdown
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
@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