我希望能够创建一个独特的系统生成的用户名。但是,mongoose findOne函数的异步性质让我感到沮丧。
我有一个generateUniqueAccountName函数,它接受一个建议的用户名,如果建议的用户名是唯一的,则检查MongoDB。如果它不唯一,则会生成新名称,直到找到唯一的用户名。
听起来很简单,但即使在找到唯一名称之前,也会退出generateUniqueAccountName。我试图使用Q(我的实现没有在这里显示),但也无法使其工作。
非常感谢任何帮助。谢谢!
这是generateUniqueAccountName函数:
/**
* 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:
.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);
这是一个示例输出:
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
看看trishalee,正如你所看到的,系统会尝试保存用户名trishalee7,即使日志显示trishalee7不是唯一名称
答案 0 :(得分:3)
您需要做的就是在return
之前添加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;
});
}