简体   繁体   中英

Mongoose validation error when using custom validator

Following is the Schema which is not working correctly with custom validator-

var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
    email : { type: String, validate: lengthValidator },
});

// Length validator for email
var lengthValidator  = function(val){
    if(val && val.length >= 6  )
        return true;
    return false;
};

var User = mongoose.model('User',userSchema);

module.exports = User;

Error -

Error: Invalid validator. Received (undefined) undefined. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate
    at SchemaString.SchemaType.validate (/MY_PROJECT_PATH/node_modules/mongoose/lib/schematype.js:416:13)
    at SchemaString.SchemaType (/MY_PROJECT_PATH/node_modules/mongoose/lib/schematype.js:38:13)
    at new SchemaString (/MY_PROJECT_PATH/node_modules/mongoose/lib/schema/string.js:24:14)
    at Function.Schema.interpretAsType (/MY_PROJECT_PATH/node_modules/mongoose/lib/schema.js:367:10)
    at Schema.path (/MY_PROJECT_PATH/node_modules/mongoose/lib/schema.js:305:29)
    at Schema.add (/MY_PROJECT_PATH/node_modules/mongoose/lib/schema.js:217:12)
    at new Schema (/MY_PROJECT_PATH/node_modules/mongoose/lib/schema.js:73:10)
    at Object.<anonymous> (/MY_PROJECT_PATH/models/users.js:2:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)

However if I remove validate then it is working correctly as I checked by changing the type from String to Number .

Let me know what i am doing wrong?

The issue you're experiencing is related to hoisting. The way that you've written your validation function means that at the time you're passing it into the schema it's an undefined value; it's not until afterwards that the variable gets set.

Here's a really basic example of the problem.

var thing = {
    foo: bar
}

var bar = function () {
    alert('hello!');
}

thing.foo();

When thing.foo() is called, it will throw an error. Why? Because this is how JavaScript interprets what I wrote:

var bar;

var thing = {
    foo: bar // At this point, bar is undefined
}

bar = function () {
    alert('hello!');
}

thing.foo();

The same thing is happening to your code. When you set the validate property in the schema to lengthValidate , it hasn't been defined yet.

There's two ways to fix it.

  1. Move the validation function definition above the schema definition in the code.
  2. Use function lengthValidator(val) instead of var lengthValidator = function(val)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM