生成可用的新用户名,始终为未定义

时间:2018-07-31 11:27:09

标签: node.js mongoose

我有一个生成可用用户名的函数,但始终返回未定义。我尝试了很多方法,在这种情况下是递归函数,但是我总是得到相同的结果,您能帮我吗?谢谢

这是代码:

function generateNewUsernameAvailable(userName, number){
  console.log('FUNCTION generateNewUsernameAvailable '+userName+' with number '+number);
  User.countDocuments({ 'userName' : userName+number }, (err, count) => {
    if (err) {
      return `Error: ${err}`;
    }
    if (count == 0) {
      return userName+number;
    }else{
      generateNewUsernameAvailable(userName, number+1);
    }});
}

module.exports.existsUserName = function(req,res){
  let userName = req.body.userName;
  console.log('POST existsUserName '+userName);
  User.countDocuments({ 'userName' : userName }, (err, count) => {
    if (err) {
      return res.status(500).send({message: `Error: ${err}`});
    }
    // Available
    if (count == 0){
      return res.status(200).send();
    } else {
      // Generate and return a new username available
      console.log(generateNewUsernameAvailable('ricardo', 1));
      res.status(400).send({message: 'newUsernameAvailable (Example ricardo1)'});
    }
  })
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,

FindOne比countDocuments / estimatedDocumentCount快。两者都是承诺,我将添加一个可能的解决方案:

function generateNewUsernameAvailable(userName, number){
  return User
  .findOne({ 'userName' : userName+number })
  .then(function(result){
    if (result){
      return generateNewUsernameAvailable(userName, number+1);
    }else{
      return userName+number;
    }
  })
  .catch(function(err) {
      console.log(`Error: ${err}`);
      throw err;
  });
}

module.exports.existsUserName = function(req,res){
  let userName = req.body.userName;
  console.log('POST existsUserName '+userName);
  User.countDocuments({ 'userName' : userName }, (err, count) => {
    if (err) {
      return res.status(500).send({message: `Error: ${err}`});
    }
    if (count == 0){
      return res.status(200).send();
    } else {
      generateNewUsernameAvailable(userName,1)
      .then(function(results){
        return res.status(400).send({message: results});
      })
      .catch(function(err){
        return res.status(500).send({message: `Error: ${err}`});
      });
    }
  })
}