I have create schema in mongoose
let userSchema = new Schema({
name: {
type: String,
required: true,
lowercase: true,
trim: true,
minLength: 4,
maxLength: 15
}
});
when I update it with this query
user.updateOne(
{ "_id" : body.id },
{ $set: {
name:body.name,
phone:body.phone,
designation:body.designation,
address:body.address
} }
).then(function (updateDate) {
var data={message:"success",data:updateDate}
callback(data)
}).catch(function (err) {
var data={message:"error",data:err}
callback(data);
});
It does not throw any error if I update string with 2 length. There are few solutions on stackoverflow but these are not working in my case
Firstly, in your schema minLength
must be minlength
, and maxLength
must be maxlength
with lowercase l.
So your schema must be like this:
let userSchema = new Schema({
name: {
type: String,
required: true,
lowercase: true,
trim: true,
minlength: 4,
maxlength: 15
}
});
Secondly, you need to add {runValidators: true}
option to updateOne.
Update validators are off by default - you need to specify the runValidators option.
So your code must be like this:
user.updateOne(
{ _id: body.id },
{
$set: {
name: body.name,
phone: body.phone,
designation: body.designation,
address: body.address
}
},
{ runValidators: true }
)
.then(function(updateDate) {
var data = { message: "success", data: updateDate };
callback(data);
})
.catch(function(err) {
var data = { message: "error", data: err };
callback(data);
});
You simple open mongodb Compass and then go to Validation option and change validation level to strict mode.
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