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

fix(document): apply virtuals to subdocuments if parent schema has virtuals: true for backwards compatibility #14774

Merged
merged 1 commit into from
Aug 7, 2024

Conversation

vkarpov15
Copy link
Collaborator

Fix #14771
Re: #14394
Re: #14623

Summary

Fixing #14771, which is a bug that was likely introduced by #14623. The issue is that older versions of Mongoose make parent virtuals option apply to subdocs presuming that the subdocs don't explicitly set virtuals.

const userLabSchema = new mongoose.Schema({
  capacityLevel: Number
});

userLabSchema.virtual('capacityLevelCeil').get(function() {
  return Math.ceil(this.capacityLevel);
});

const labPlotSchema = new mongoose.Schema({
  plotId: Number,
  lab: userLabSchema
});

const userSchema = new mongoose.Schema({
  username: String,
  labPlots: [labPlotSchema]
}, { toObject: { virtuals: true } });

const User = mongoose.model('User', userSchema);

const doc = new User({
  username: 'test',
  labPlots: [{
    plotId: 1,
    lab: { capacityLevel: 3.14 }
  }]
});
// In Mongoose 8.4.0, virtual is applied because top-level schema has `toObject: { virtuals: true }`
// In Mongoose 8.5.2, virtual is not applied because `userLabSchema` does not have `toObject: { virtuals: true }`
console.log(doc.toObject().labPlots[0].lab.capacityLevelCeil);

Examples

…irtuals: true` for backwards compatibility

Fix #14771
Re: #14394
Re: #14623
@vkarpov15 vkarpov15 added this to the 8.5.3 milestone Aug 1, 2024
@vkarpov15 vkarpov15 merged commit a206eef into master Aug 7, 2024
46 checks passed
@vkarpov15 vkarpov15 deleted the vkarpov15/gh-14771 branch August 7, 2024 22:30
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.

Virtuals not serialized after v8.5
3 participants