2

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

6
  • Why can't you just not overwrite that property? Commented Aug 23, 2017 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. Commented Aug 23, 2017 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. Commented Aug 23, 2017 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. Commented Aug 24, 2017 at 0:07
  • Note that my question, is pretty similar to this question - stackoverflow.com/questions/24824657/… Commented Aug 24, 2017 at 0:07

1 Answer 1

3

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'); } }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.