对于Node API,我必须生成一个随机的字母数字键,该键应该是唯一且简短的(我不能同时使用uuid或Mongo ObjectID)。
我认为这种逻辑:
然后,我尝试了:
do {
key = randomKey(8);
newGroup.key = key;
Group.findOne({numberId: key}).then(function (foundGroup) {
console.log("cb");
if (! foundGroup) {
console.log("not found")
notUnique = false;
}
}).catch(function (err) {
return response.send(500);
});
} while (notUnique);
但是,只有我是一个无限循环,notUnique
是永远不会切换到true
。以防万一,这是针对一个Empy数据库进行测试的。
我怎么能做到呢?
您可以使用异步模块轻松完成此操作:
var async = require('async')
async.forever(
function(next) {
key = randomKey(8);
Group.findOne({numberId: key}).then(function (foundGroup) {
console.log("cb");
if (! foundGroup) {
console.log("not found")
notUnique = false;
next(new Error(), key) // break forever loop with empty error message and the key
}
else
return next() //continue loop
}).catch(function (err) {
next(err); //break loop
return response.send(500);
});
},
function(err, key) {
if(key){
newGroup.key = key;
}
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句