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 .
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
}
}
There is no functionality to prevent from update
You can do by removing
body
delete req.body.email;
const customer = await Customer.findOneAndUpdate({_id : req.params.id}, req.body);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With