eagor
eagor

Reputation: 10035

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?

Upvotes: 8

Views: 3485

Answers (2)

Suhail Akhtar
Suhail Akhtar

Reputation: 2023

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

Upvotes: 4

eagor
eagor

Reputation: 10035

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

Upvotes: 15

Related Questions