我试图在NodeJS/express‘s/MongoDB/Mongoose应用程序中使用验证器和快速验证器来确认用户没有使用已经注册的电子邮件地址。我已经在电子邮件字段上有了一个独特的索引,但我想做的是使用一种方法将所有的验证都保存在一个地方。因此,我的问题:使用快速验证器验证唯一性。
我已经创建了模式方法来查找电子邮件地址,并且它正在工作。我已经创建了自定义验证器,并将其连接到控制器中。它也在起作用。我的问题是,我不知道如何与控制器中的验证器通信来自回调的模式方法的结果。
user.js (模型)
...
/**
* Check for email addresses already in the collection
*/
checkEmailDupes: function(req, cb) {
this.model('User').findOne({email: req}, function (err, user) {
if (err) {
return cb(err);
}
cb(null, user); // this is passing back the expected result
});
},
...
users.js (控制器)
...
// The call to the custom validator (shown below)
req.assert('email', 'Email must be unique').checkEmailDupes(user);
...
// Check for email addresses that are already registered
expressValidator.Validator.prototype.checkEmailDupes = function(user) {
user.checkEmailDupes(this.str, function (err, result) {
if (err) {
console.log('An error occurred in checkEmailDupes');
}
else {
console.log('Found a user in checkEmailDupes');
console.log(result); // this is producing the expected result
}
});
return this.error(this.msg || 'Looks like this email address has already been registered');
return this;
}
我知道return this.error(this.msg...)
需要去别的地方。理想情况下,我会把它加入回调,但是当我这样做的时候
TypeError:对象#没有方法‘错误’
发布于 2013-09-30 09:13:28
我最终无法使这种方法发挥作用。由于@robertklep和他的反馈,我决定使用mongo传回的错误代码(在找到电子邮件的非唯一值的情况下,它是MongoError: E11000 duplicate key error index
),并基于此设置错误消息。
它最终看起来如下(在用户控制器中):
user.save(function(err) {
if (err) {
// Instantiate the errors array
var errors = [];
// Email address already in DB
if (err.code == 11000) {
// Build the error object
var error = {
param: 'email',
msg: 'The email address entered has already been registered',
value: ''
};
// Push the error onto the errors array
errors.push(error);
}
return res.render('users/signup', {
errors: errors,
user: user
});
}
...
发布于 2013-09-29 23:58:19
尝试这样做(所做的是使用已经“填充”的范围和第一个参数创建一个部分error
函数):
expressValidator.Validator.prototype.checkEmailDupes = function(user) {
var error = this.error.bind(this, this.msg || 'Looks like this email address has already been registered');
user.checkEmailDupes(this.str, function (err, result) {
if (err) {
console.log('An error occurred in checkEmailDupes');
return error();
}
else {
console.log('Found a user in checkEmailDupes');
console.log(result); // this is producing the expected result
}
});
return this;
}
但是,这里可能有一些问题,因为user.checkEmailDupes
是异步的,但expressValidator.Validator.prototype.checkEmailDupes
不是异步的,我不知道验证器模块的内部工作方式是否存在问题。
编辑:也许我刚才给的this answer也有用。使用express-validator
验证数据库约束可能不是最佳解决方案。
https://stackoverflow.com/questions/19084648
复制