var post = mongoose.Schema({
...
_createdOn: Date
});
I want to allow setting the _createdOn
field only upon document creation, and disallow changing it on future updates. How is it done in Mongoose?
I achieved this effect by setting the _createdOn
in the schema's pre-save hook (only upon first save):
schema.pre('save', function (next) {
if (!this._createdOn) {
this._createdOn = new Date();
}
next();
});
... and disallowing changes from anywhere else:
userSchema.pre('validate', function (next) {
if (this.isModified('_createdOn')) {
this.invalidate('_createdOn');
}
next();
});
Check this answer: https://stackoverflow.com/a/63917295/6613333
You can make the field as immutable.
var post = mongoose.Schema({
...
_createdOn: { type: Date, immutable: true }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With