简体   繁体   English

猫鼬/节点如果存在文档,则编辑数据,然后重新提交

[英]Mongoose/Node If document exists, edit data, resubmit

I'm trying to create a Mongo Document using Mongoose and Node. 我正在尝试使用Mongoose和Node创建一个Mongo文档。 However, I want to know that it is unique and if it isn't then add a count. 但是,我想知道它是唯一的,如果不是,则添加一个计数。

A simple example would be, create a user with a username. 一个简单的例子就是用用户名创建一个用户。 If username John is taken, iterate through and create one with John1. 如果使用用户名John,则遍历并使用John1创建一个。 However, if John1 is taken, keep going through until JohnX is free and then save the document. 但是,如果采用了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 .....
               ....
            }
         });
    }

This current code ends up going into an infinite loop. 当前代码最终陷入无限循环。 If I remove the While loop my console.log executes, however, when I put it back into the while loop, it doesn't seem to hit my console.log. 但是,如果我删除了While循环,我的console.log将执行,但是当我将其放回while循环中时,它似乎并没有命中我的console.log。 Would really appreciate any insights. 非常感谢任何见解。

Here could be one workaround, using distinct to find all username , then sort it to get the max username, then save this new username record. 这可能是一种解决方法,使用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) {});
     }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM