I'm currently working on a solution to check if a username already exists in my MongoDB database. If it does, I need to add a random number to it and then keep checking until a unique name is found.
Below is the code snippet that I've been using:
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 found!");
name = x;
});
});
callback();
}
Once a unique name is obtained, I want to insert a new document into the database. Below is the function call with the `db insert` as the callback:
changeName(name, function(){
db.collection('users').insertOne({
"user" : name, "email": account.email, "createdAt":new Date()
});
});
The issue I'm facing is that the original name is being sent to the database instead of the modified one. I thought utilizing a callback would solve this problem, but it seems like there might be an issue with how I'm implementing it. Any assistance or guidance would be greatly appreciated.