-
-
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
Getter is not applied when schema changes from string to nested schema #15301
Comments
This is a somewhat tricky issue because Mongoose sets Our recommended approach is to use a userSchema.pre('init', function(rawDoc) {
if (typeof rawDoc.time === 'string') {
rawDoc.time = timeStringToObject(rawDoc.time);
}
}); Below is a full script. import mongoose, { Schema } from 'mongoose';
await mongoose.connect('mongodb://127.0.0.1:27017/mongoose_test');
const timeStringToObject = (time) => {
if (typeof time !== "string") return time;
const [hours, minutes] = time.split(":");
return { hours: parseInt(hours), minutes: parseInt(minutes) };
};
const oldUserSchema = new Schema(
{
time: {
type: String,
required: true,
},
},
{}
);
const UserModelName = "User";
const OldUser = mongoose.model(UserModelName, oldUserSchema);
await OldUser.deleteMany({});
await OldUser.create({ time: "12:34" });
mongoose.deleteModel(UserModelName);
const userSchema = new Schema({
time: {
type: new Schema(
{
hours: { type: Number, required: true },
minutes: { type: Number, required: true },
},
{ _id: false }
),
required: true
},
});
userSchema.pre('init', function(rawDoc) {
if (typeof rawDoc.time === 'string') {
rawDoc.time = timeStringToObject(rawDoc.time);
}
});
const User = mongoose.model(UserModelName, userSchema);
await User.create({ time: { hours: 12, minutes: 35 } });
const usersLean = await User.find().lean({ getters: true });
console.log(
usersLean,
await User.findOne(),
(await User.find()).map((doc) => doc.toObject({ getters: true }))
); A note of caution: if |
Prerequisites
Mongoose version
^8.12.1
Node.js version
22.13.9
MongoDB server version
"mongodb-memory-server": "^10.1.4"
Typescript version (if applicable)
^5.8.2
Description
I am trying to migrate a schema from a string to a nested schema object. The getter works, but the new value is not applied to the returned document.
When using toObject with getters, the time string is removed but no new value is applied:
When using lean getters with the
"mongoose-lean-getters: "^2.2.1"
plugin, the time string is not replaced.Steps to Reproduce
Reproduction code:
Expected Behavior
I expect the string to be replaced by the new object.
The text was updated successfully, but these errors were encountered: