Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a field update in moongoose

I have a schema that looks like this :

"use strict"

const mongoose = require('mongoose');
const timestamp  = require('mongoose-timestamp');

const CustomerSchema = new mongoose.Schema({
    name : {
        type : String,
        required : true,
        trim : true
    },
    email : {
        type : String,
        required : true,
        trim : true
    },
    balance : {
        type : Number ,
        default : 0
    }
})

//use timestamps to add created at and updated at
CustomerSchema.plugin(timestamp);

const Customer = mongoose.model('Customer',CustomerSchema);

module.exports = Customer;

When I want to run an update , I run this code

const Customer = require('../models/Customer');
const customer =  await Customer.findOneAndUpdate({_id : req.params.id}, req.body);

so req.body carries the data that will be updated The problem is that I do not want people to update the email field .

So my question is :

How do I lock the email field from being updated . Is there a way to lock it in the schema , so that it can only be added initially but not updated later ?

Thanks .

like image 257
Daggie Blanqx - Douglas Mwangi Avatar asked Dec 17 '22 20:12

Daggie Blanqx - Douglas Mwangi


2 Answers

There is a property you can define at the schema level called immutable.

Reference to documentation: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-immutable

So your schema would look like this:

const CustomerSchema = new mongoose.Schema({
    name : {
        type : String,
        required : true,
        trim : true
    },
    email : {
        type : String,
        required : true,
        trim : true,
        immutable: true // ADD THIS PROPERTY HERE
    },
    balance : {
        type : Number ,
        default : 0
    }
}
like image 198
Michał Pierzchlewicz Avatar answered Jan 04 '23 04:01

Michał Pierzchlewicz


There is no functionality to prevent from update

You can do by removing email object from body

delete req.body.email;
const customer =  await Customer.findOneAndUpdate({_id : req.params.id}, req.body);
like image 32
IftekharDani Avatar answered Jan 04 '23 02:01

IftekharDani