Alexander Mills
Alexander Mills

Reputation: 100000

Prevent field from being updated after initial set

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

Upvotes: 2

Views: 823

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

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');
    }
});

Upvotes: 3

Related Questions