Using Mongoose or the plain MongoDB driver, is there a way to lock a field from being updated after that field is first set?
1 Answer
Answer by @eagor here.
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 (self.isModified('_createdOn')) { self.invalidate('_createdOn'); } });
Model.update(condition, data, options, cb), then I can't prevent changing the field for a pre-existing document.