7
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?

eagor
  • 9,150
  • 8
  • 47
  • 50

2 Answers2

15

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();
});
squaleLis
  • 6,116
  • 2
  • 22
  • 30
eagor
  • 9,150
  • 8
  • 47
  • 50
3

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 }
});
Suhail Akhtar
  • 1,718
  • 15
  • 29