2016-11-21 1 views
0

私は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 insertで呼び出される関数を次に示します。

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

問題は元の名前がdbに送信されていることです。コールバックの使用は私がここに必要なものだと思っていましたが、おそらく私はそれを正しく使用していません。どんな助力も非常に感謝しています。

答えて

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 
    } 
長すぎました
関連する問題