Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose expand default validation

I want to build "minLength" and "maxLength" in the mongoose schema validation rules, the current solution is:

var blogSchema = new Schema({
  title: { required: true, type: String }
});

blogSchema.path('title').validate(function(value) {
  if (value.length < 8 || value.length > 32) return next(new Error('length'));
});

However I think this should be simplified by just adding custom schema rules like so:

var blogSchema = new Schema({
    title: {
        type: String,
        required: true,
        minLength: 8,
        maxLength: 32
    }
});

How can I do this, is this even possible?

like image 329
onlineracoon Avatar asked Nov 30 '22 04:11

onlineracoon


1 Answers

Check out the library mongoose-validator. It integrates the node-validator library for use within mongoose schemas in a very similar way to which you have described.

Specifically, the node-validator len or min and max methods should provide the logic you require.

Try :

var validate = require('mongoose-validator').validate;

var blogSchema = new Schema({
 title: {
    type: String,
    required: true,
    validate: validate('len', 8, 32)
 }
});
like image 171
Rob Squires Avatar answered Dec 02 '22 18:12

Rob Squires