Mongoose: prevent updating certain fields

var post = mongoose.Schema({ ... _createdOn: Date }); 

I want to allow the setting of the _createdOn field only when creating the document and prevent it from changing for future updates. How is this done in Mongoose?

+5
source share
1 answer

I achieved this effect by setting _createdOn to pre-save the schema (only on the first save):

 schema.pre('save', function(next) { if (!this._createdOn) { this._createdOn = new Date(); } next(); }); 

... and the prohibition of changes from another place:

 userSchema.pre('validate', function(next) { if (self.isModified('_createdOn')) { self.invalidate('_createdOn'); } }); 
+9
source

Source: https://habr.com/ru/post/1204563/


All Articles