簡體   English   中英

貓鼬/節點如果存在文檔,則編輯數據,然后重新提交

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

我正在嘗試使用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。 非常感謝任何見解。

這可能是一種解決方法,使用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