简体   繁体   中英

Mongoose/Node If document exists, edit data, resubmit

I'm trying to create a Mongo Document using Mongoose and Node. 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. However, if John1 is taken, keep going through until JohnX is free and then save the document.

    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. 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.

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) {});
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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