0

如果我尝试注册一个重复的用户名,一切正常,除了错误消息说它已经注册。所有其他错误消息都有效;只是不是这个。

router.post('/register', function(req, res){
var name = req.body.name;
var email = req.body.email;
// var username = req.body.username;
var username = req.body.name;
var password = req.body.password;
var password2 = req.body.password2;

req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('name', 'This name is already registered.')
.custom(function(name, req){
    return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
            console.log(name);
            console.log(user);
            if (err) throw err;
            if(user == null) {
                resolve();
            } else {
                console.log('rejecting');
                reject();
            }
        });
    });
}); 

req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
// req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
    res.render('register',{
        errors:errors
    });
} else {
    var newUser = new User({
        name: name,

我错过了什么?

4

1 回答 1

0

我很确定您custom()在代码中链接的方式仅适用于新 API。否则,您正在使用旧版 API。对于遗留 API,您必须在应用中间件时定义自定义验证器(在 app.js 或类似的东西中)。例如:

app.use(expressValidator({
  customValidators: {
    isUniqueName: function(name) {
      return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
          console.log(name);
          console.log(user);
          if (err) throw err;
          if (user == null) {
            resolve();
          } else {
            console.log('rejecting');
            reject();
          }
        });
      });
    },
  },
}));

在控制器中:

req.checkBody('name', 'This name is already registered.').isUniqueName();

我通常会建议更改为新的 API。当您已经知道要验证的内容时,不应该花费太多时间。它在这里写了更多关于它的内容。

于 2017-11-13T19:00:06.667 回答