Mongoose / Node如果文档存在,编辑数据,重新提交

时间:2016-03-12 00:18:48

标签: node.js mongodb mongoose

我正在尝试使用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。非常感谢任何见解。

1 个答案:

答案 0 :(得分:0)

以下是一种解决方法,使用distinct查找所有0x5101,然后对其进行排序以获取最大用户名,然后保存此新用户名记录。

username