使用自定义验证程序时出现Mongoose验证错误

时间:2014-04-17 09:18:30

标签: node.js mongodb mongoose

以下是使用自定义验证程序无效的Schema -

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: 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)

但是,如果我删除了validate,那么当我通过将类型从String更改为Number来检查时它是否正常工作。

让我知道我做错了什么?

1 个答案:

答案 0 :(得分:5)

您遇到的问题与提升有关。你编写验证函数的方式意味着当你将它传递给模式时,它是一个未定义的值;直到之后变量才被设置。

这是问题的一个非常基本的例子。

var thing = {
    foo: bar
}

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

thing.foo();

调用thing.foo()时,会抛出错误。为什么?因为这就是JavaScript解释我所写内容的方式:

var bar;

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

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

thing.foo();

您的代码也发生了同样的事情。将架构中的validate属性设置为lengthValidate时,尚未定义它。

有两种方法可以解决它。

  1. 将验证函数定义移到代码中的架构定义之上。
  2. 使用function lengthValidator(val)代替var lengthValidator = function(val)
相关问题