Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose: disallow updating of specific fields

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

I want to allow setting the _createdOn field only upon document creation, and disallow changing it on future updates. How is it done in Mongoose?

like image 945
eagor Avatar asked Oct 13 '14 14:10

eagor


2 Answers

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 (this.isModified('_createdOn')) {
        this.invalidate('_createdOn');
    }
    next();
});
like image 186
eagor Avatar answered Nov 09 '22 17:11

eagor


Check this answer: https://stackoverflow.com/a/63917295/6613333

You can make the field as immutable.

var post = mongoose.Schema({
    ...
    _createdOn: { type: Date, immutable: true }
});
like image 3
Suhail AKhtar Avatar answered Nov 09 '22 17:11

Suhail AKhtar