我正在尝试使用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 循环.log则会执行,但是,当我将其放回 while 循环时,它似乎没有击中我的控制台.log。 真的很感激任何见解。
这可能是一种解决方法,使用 distinct
查找所有username
,然后对其进行排序以获取最大用户名,然后保存此新用户名记录。
Record.distinct('username', function(err, usernames){
if (err)
console.log(err);
else {
// sort the username, then pop the last name
var un = usernames.sort().pop();
var reg = /d+/g;
// get the current max number in username,
var num = parseInt(un.match(reg)[0]);
var newusername = 'John' + (++num);
// insert new username record
var r = new Record({username: newusername});
r.save(function(err) {});
}
});