-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Virtuals not serialized after v8.5 #14771
Comments
Repro script: 'use strict';
const mongoose = require('mongoose');
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 }
}]
});
console.log(doc.toObject().labPlots[0]); Output:
|
It looks like, in older versions of Mongoose, schema-level @Schema({
toObject: {
getters: true,
},
toJSON: {
getters: true,
},
}) With const userLabSchema = new mongoose.Schema({
capacityLevel: Number
}, { toObject: { virtuals: true } }); // <-- added `virtuals: true` here
userLabSchema.virtual('capacityLevelCeil').get(function() {
return Math.ceil(this.capacityLevel);
}); |
Thanks @vkarpov15 🙌 that makes sense, not sure why I didn't try if that would fix the issue. |
fix(document): apply virtuals to subdocuments if parent schema has `virtuals: true` for backwards compatibility
Prerequisites
Mongoose version
8.5.2
Node.js version
v22.5.1
MongoDB server version
7.0.12
Typescript version (if applicable)
5.5.4
Description
I have a nested schema, that contains calculated (virtual) props based on level. After updating from 8.4.5 to 8.5.2, the virtuals are no longer serialized. I'm using Mongoose with
@nestjs/mongoose
if that matters, it hasn't been updated since.v8.4.5
v8.5.2
Steps to Reproduce
Update to v8.5.2
Expected Behavior
Virtuals should be serialized.
The text was updated successfully, but these errors were encountered: