自定义验证程序,用于检查用户名是否为唯一

时间:2017-12-10 14:31:13

标签: javascript node.js mongodb validation asynchronous

我正在使用 express-validator 来验证我的表单 除了检查用户名是否唯一之外,我能够验证所有内容。

由于我正在为 MongoDB 使用 Mongoose ,因此搜索数据库是异步的。

  • 如何创建自定义验证程序以检查用户名是否唯一?

这是我搜索数据库的方式:

// Call the model function to find a user by their username
User.getUserByUsername(username, function(error, user) {
    if ( error ) throw error; // If there is an error throw it
});

这是 getUserByUsername 函数:

module.exports.getUserByUsername = function(username, callback) { // Find a user by their username
    var query = {username: username}; // Set the query to search for matching usernames
    User.findOne(query, callback); // Find one object with the given query and call the callback function
}

我不确定如何将其合并到Custom Express Validator中。我尝试过这样的事情:

app.use(validator( { // Use Express Validator
      customValidators: { // Create custom validators
        usernameExists: function( username ) { // Create a validator with the name of 'usernameExists' and make it a function
          User.getUserByUsername(username, function(err, user) { // Call the model function to find a user by their username
            if ( err ) throw err; // If there is an error throw it
            if(!user) { // If the user doesn't exist
                // Return false
            }
            // Otherwise Return true
          });
        }
      }
} ));

这里的问题是 getUserByUsername 是异步的,这意味着我可以 NOT 从该函数内部使用 return

稍后,我会使用这样的自定义验证器:

req.checkBody('username', 'Username is already registered.').usernameExists( req.body.username ); // If the username already exists
  • 如何正确返回自定义验证器?我尝试使用承诺,但未成功。

0 个答案:

没有答案