如何在MongoDB中强制使用唯一的用户名?

时间:2016-11-21 22:18:45

标签: javascript mongodb

我试图找到我的MongoDB中是否已经存在用户名,如果已存在,则向其添加一个随机数,然后再次使用添加的随机数进行检查,并继续检查直到找不到匹配项。

以下是我目前的代码:

function changeName(x, callback){
    MongoClient.connect(URI, function(err, db){
        db.collection('users').findOne({"user": x}, function(err, result){
            if (err) throw err;
            if (result !== null){
                console.log("match found, changing name...");
                if(result.user){console.log("result.user = " + result.user)}
                //change name.
                x = x + Math.floor(Math.random()*9);
                changeName(x,function(){console.log("callback")});
            }
            console.log("x = " + x);
            console.log("no match!");
            name = x;
        });
    });
    callback();
}

然后,一旦名称更改为唯一名称,我想在db中创建一个新文档。这是使用db insert作为回调函数调用的函数:

changeName(name, function(){    
    db.collection('users').insertOne({
        "user" : name, "email": account.email, "createdAt":new Date()
    });
});

问题是原始名称是发送到数据库的内容。我认为使用回调是我需要的,但也许我没有正确使用它。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我想把它写成评论,因为这可能不是合适的答案,但文字太长了

var cb;
    function changeName(x, callback){
        if(callback) {cb = callback;} //dirty hack
        MongoClient.connect(URI, function(err, db){
            db.collection('users').findOne({"user": x}, function(err, result){
                if (err) throw err;
                if (result !== null){
                    console.log("match found, changing name...");
                    if(result.user){console.log("result.user = " + result.user)}
                    //change name.
                    x = x + Math.floor(Math.random()*9);
                    changeName(x);
                    //the function(){console.log} was overriding callback
                }
                console.log("x = " + x);
                console.log("no match!");
                name = x;
            });
        });
        cb(); //the cached function gets called
    }