1

Here is my schema of mongoose where , deptName is unique , but I want it case sensitive too for example if xyz is save in db then XYZ should not save .

var department = mongoose.Schema({
    deptName: {
        type: String,
        unique: true,
        required: true
    },
    deptHead: {
        type: mongoose.Schema.ObjectId,
        ref: 'employee'
    },
    active: {
        type: Boolean,
        default: true
    }
});
  • I think you mean case **in**sensitive? Like this question: http://stackoverflow.com/questions/13991604/mongoose-schema-validating-unique-field-case-insensitive – JohnnyHK Feb 16 '16 at 13:47
  • @JohnnyHK, I test `lowercase` in Mongoose v4.4.3, it will convert the `XYZ` to `xyz`, and save it to db... maybe custom validate should be better... – zangw Feb 17 '16 at 03:23

1 Answers1

0

Try to do it through lowercase in the String validation. Add lowercase to your schema as below

var departmentSchema = mongoose.Schema({
    deptName: {
        type: String,
        unique: true,
        required: true,
        lowercase: true
    }
});

When you try to save XYZ to deptName. The validation should be failed and cannot save this document into collection.

However, I test it in the Mongoose v4.4.3 with following codes

var d = new Depart({
    deptName: 'XYZAA'
});

d.save(function(err) {
    if (err)
        console.log(err);
    else
        console.log('Save department successfully...');
});

And it could save the document successfully and convert XYZ to xyz

{ "_id" : ObjectId("56c3dae36a4d4f041548f7e0"), "deptName" : "xyz", "__v" : 0 }

Anther way to custom the validation as following

var departmentSchema = mongoose.Schema({
    deptName: {
        type: String,
        unique: true,
        required: true,
        validate: {
          validator: function(v) {
            if (v && v.length)
                var re = /^[a-z]$/i; 
                return re.test(v);
          },
        }
    }
});

When try to save XYZ to deptname, validation error will come up.

{ [ValidationError: Depart validation failed]
  message: 'Depart validation failed',
  name: 'ValidationError',
  errors:
   { deptName:
      { [ValidatorError: Validator failed for path `deptName` with value `XYZ`]
        properties: [Object],
        message: 'Validator failed for path `deptName` with value `XYZ`',
        name: 'ValidatorError',
        kind: 'user defined',
        path: 'deptName',
        value: 'XYZ' } } }
zangw
  • 43,869
  • 19
  • 177
  • 214