Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minlength validator not working in mongoose

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

like image 786
Imran Afzal Avatar asked Oct 20 '25 03:10

Imran Afzal


2 Answers

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);
    });
like image 155
SuleymanSah Avatar answered Oct 21 '25 15:10

SuleymanSah


You simple open mongodb Compass and then go to Validation option and change validation level to strict mode.

like image 41
Fazal Ur Rehman Fazal Avatar answered Oct 21 '25 15:10

Fazal Ur Rehman Fazal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!