1

Using Mongoose or the plain MongoDB driver, is there a way to lock a field from being updated after that field is first set?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Why can't you just not overwrite that property? – Kevin Smith Aug 23 '17 at 23:14
  • Our business logic dictates that the first value is the correct one. Any changes to that value are to be ignored; but we can update other fields in the document, just not that particular field. It's sort of like the _id field, after all. – Alexander Mills Aug 23 '17 at 23:17
  • Just never change it throughout the software you are writing? (you can ensure this business logic in the tests wrapping the update operations. also If you're always using the update operators and not doing blanket document replaces (which you shouldn't do) then you'll be fine. – Kevin Smith Aug 23 '17 at 23:19
  • doing this at the application level is kind of a pain. The problem is if I write an update query, such as `Model.update(condition, data, options, cb)`, then I can't prevent changing the field for a pre-existing document. – Alexander Mills Aug 24 '17 at 00:07
  • Note that my question, is pretty similar to this question - https://stackoverflow.com/questions/24824657/how-do-i-update-mongodb-document-fields-only-if-they-dont-exist – Alexander Mills Aug 24 '17 at 00:07
  • This question is basically the other side of the same coin as the question I just linked to. – Alexander Mills Aug 24 '17 at 00:08

1 Answers1

2

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');
    }
});
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69