Tolsee
Tolsee

Reputation: 1705

How to make some fields not updatable once saved in mongoose?

I have build a schema as follows:

const UserInfoSchema = new Schema({
    email: { type: String, required: true, unique: true },
    username: { type: String, required: true, unique: true },
    userId: { type: Schema.Types.ObjectId, ref: 'User'},
    displayName: { type: String, required: true },
    profilePic: {
        filename: {type: String},
        url: {type: String}
    },
    created_at: Date,
    updated_at: Date
})

What I need here is once the fields such as email, username and userId are saved, should not be modified. Is there anything pre-build in mongoose for this kind of feature?

I have done some research on schema.pre('update', (next) => {}), but got nothing really useful/don't know if one can use for the mentioned feature. Any help on this matter is greatly appreciated. Thanks in advance.

Upvotes: 4

Views: 1291

Answers (2)

Filipe Pinheiro
Filipe Pinheiro

Reputation: 53

There is an easier way when you save the Schema, you can set the field as immutable, like this

const UserInfoSchema = new Schema({
    email: { type: String, required: true, unique: true, immutable:true },
    username: { type: String, required: true, unique: true, immutable:true },
    userId: { type: Schema.Types.ObjectId, ref: 'User', immutable:true},
    displayName: { type: String, required: true },
    profilePic: {
        filename: {type: String},
        url: {type: String}
    },
    created_at: Date,
    updated_at: Date
})

it won't throw any error, if you want it you should check it elsewhere, but when you try to modify the immutable fields, it wont be changed at all

Upvotes: 5

LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8818

for(const key in userUpdates) {
    switch(key)  { 
        case 'username':
        case 'email':
            throw new Error('These field/s cannot be changed anymore');
    }
}
User.findByIdAndUpdate(id, userUpdates, { new: true, runValidators: true });

Upvotes: 0

Related Questions