最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose and NodeJS: Creating a unique system-generated username - Stack Overflow

programmeradmin0浏览0评论

I want to be able to create a system-generated username that is unique. However, the async nature of the mongoose findOne function is tripping me up.

I have a generateUniqueAccountName function that takes in a proposed username and checks with MongoDB if the proposed username is unique. If it is not unique, then a new name is generated until a unique username is found.

Sounds simple enough but generateUniqueAccountName is exited even before a unique name is found. I tried to use Q (my implementation is not shown here) but couldn't make it work either.

Would appreciate any help. Thanks!

This is the generateUniqueAccountName function:

 /**
 * Returns a unique account name based on proposed name
 * @param {String} proposedName
 * @return {Promise}
 */
function generateUniqueAccountName(proposedName) {

  return Account.findOne({accountName: proposedName})
      .then(function(account) {
        if (account != null) {
          console.log('no can do try again: ' + proposedName);
          proposedName += Math.floor((Math.random() * 100) + 1);
          generateUniqueAccountName(proposedName);
        } else {
          console.log('proposed name is unique' + proposedName);
        }
        return proposedName;
      })
      .catch(function(err) {
        console.error(err);
        throw err;
      });
 }

generateUniqueAccountName is called like so:

.then(function(newAccount) {
   // Next generate a unique account name
   console.log('Generating unique account name ...');
   let proposedName = (accounts[i].acctFName + accounts[i].acctLName)
                         .replace(/\s/g, '');

   return generateUniqueAccountName(proposedName.toLowerCase())
            .then(function(accountName) {
               console.log('the unique name is ' + accountName);
               newAccount.accountName = accountName;
               return newAccount;
             })
            .catch(function(err) {
               throw err;
             });
})
.then(saving_part);

This is a sample output:

Generating unique account name ...
no can do try again: teylim
no can do try again: michaelalee
no can do try again: joeykwa
the unique name is teylim86
the unique name is michaelalee72
the unique name is joeykwa91
no can do try again: trishalee
the unique name is trishalee7
proposed name: michaelalee72 is unique
proposed name: joeykwa91 is unique
no can do try again: teylim86
no can do try again: trishalee7
proposed name: teylim8641 is unique
proposed name: trishalee734 is unique
Saving account trishalee7

Looking at trishalee, as you can see, the system tries to save the username trishalee7 even though as the log has shown trishalee7 is not a unique name

I want to be able to create a system-generated username that is unique. However, the async nature of the mongoose findOne function is tripping me up.

I have a generateUniqueAccountName function that takes in a proposed username and checks with MongoDB if the proposed username is unique. If it is not unique, then a new name is generated until a unique username is found.

Sounds simple enough but generateUniqueAccountName is exited even before a unique name is found. I tried to use Q (my implementation is not shown here) but couldn't make it work either.

Would appreciate any help. Thanks!

This is the generateUniqueAccountName function:

 /**
 * Returns a unique account name based on proposed name
 * @param {String} proposedName
 * @return {Promise}
 */
function generateUniqueAccountName(proposedName) {

  return Account.findOne({accountName: proposedName})
      .then(function(account) {
        if (account != null) {
          console.log('no can do try again: ' + proposedName);
          proposedName += Math.floor((Math.random() * 100) + 1);
          generateUniqueAccountName(proposedName);
        } else {
          console.log('proposed name is unique' + proposedName);
        }
        return proposedName;
      })
      .catch(function(err) {
        console.error(err);
        throw err;
      });
 }

generateUniqueAccountName is called like so:

.then(function(newAccount) {
   // Next generate a unique account name
   console.log('Generating unique account name ...');
   let proposedName = (accounts[i].acctFName + accounts[i].acctLName)
                         .replace(/\s/g, '');

   return generateUniqueAccountName(proposedName.toLowerCase())
            .then(function(accountName) {
               console.log('the unique name is ' + accountName);
               newAccount.accountName = accountName;
               return newAccount;
             })
            .catch(function(err) {
               throw err;
             });
})
.then(saving_part);

This is a sample output:

Generating unique account name ...
no can do try again: teylim
no can do try again: michaelalee
no can do try again: joeykwa
the unique name is teylim86
the unique name is michaelalee72
the unique name is joeykwa91
no can do try again: trishalee
the unique name is trishalee7
proposed name: michaelalee72 is unique
proposed name: joeykwa91 is unique
no can do try again: teylim86
no can do try again: trishalee7
proposed name: teylim8641 is unique
proposed name: trishalee734 is unique
Saving account trishalee7

Looking at trishalee, as you can see, the system tries to save the username trishalee7 even though as the log has shown trishalee7 is not a unique name

Share Improve this question asked Sep 20, 2017 at 15:46 fabfab 4827 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

All what you need to do is to add return statement before generateUniqueAccountName(proposedName):

function generateUniqueAccountName(proposedName) {
  return Account
    .findOne({accountName: proposedName})
    .then(function(account) {
      if (account) {
        console.log('no can do try again: ' + proposedName);
        proposedName += Math.floor((Math.random() * 100) + 1);
        return generateUniqueAccountName(proposedName); // <== return statement here
      }
      console.log('proposed name is unique' + proposedName);
      return proposedName;
    })
    .catch(function(err) {
      console.error(err);
      throw err;
    });
}
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>