我正在尝试使用Mongoose和Node创建一个Mongo文档。但是,我想知道它是唯一的,如果不是,那么添加一个计数。
一个简单的例子是,用用户名创建用户。如果使用了用户名John,则迭代并使用John1创建一个。但是,如果采用John1,请继续操作直到JohnX空闲,然后保存文档。
var record = new Record();
record.name = 'John';
record.username = 'John';
var keepGoing = true;
var x=1;
while(keepGoing){
Record.findOne({username: record.username}, function(err, result){
console.log('Check I get here');
if(result!=null){
// User Exists, try a new username;
record.username = 'John' + x;
x++;
}
else{
keepGoing= false;
record.save .....
....
}
});
}
此当前代码最终进入无限循环。如果我删除了While循环,我的console.log会执行,但是,当我把它放回while循环时,它似乎没有打到我的console.log。非常感谢任何见解。