Ensuring Uniqueness of Usernames in MongoDB

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.

Answer №1

My intention was to leave this as a comment due to uncertainty about it being the correct solution, but the explanation ended up too lengthy

let callbackFunction;
    function updateName(input, callback){
        if(callback) {callbackFunction = callback;} //using a workaround
        MongoClient.connect(URI, function(err, db){
            db.collection('users').findOne({"user": input}, function(err, result){
                if (err) throw err;
                if (result !== null){
                    console.log("Match found, updating name...");
                    if(result.user){console.log("result.user = " + result.user)}
                    //modify name.
                    input = input + Math.floor(Math.random()*9);
                    updateName(input);
                    //the function(){console.log} was replacing the callback
                }
                console.log("input = " + input);
                console.log("No match found!");
                name = input;
            });
        });
        callbackFunction(); //execute the saved function
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for extracting tables from a document using Node.js

When converting an XML document to JSON using the xml-js library, one of the attributes includes HTML markup. After parsing, I end up with JSON that contains HTML within the "description":"_text": field. { "name": { ...

What is the reason for the Circle to Polygon node module producing an oval or ellipse shape instead of a circle shape?

I've been experimenting with the npm package circle-to-polygon and I crafted the following code to generate a polygon that resembles a circle. const circleToPolygon = require('circle-to-polygon'); let coordinates = [28.612484207825005, 77. ...

There are errors occurring in the getter I created within the vuex store.js file

Currently utilizing vuejs, vuex, and vuetify. Within this project there are 3 files in play and I will share the key sections here. The main objective is to showcase data associated with the route parameter. Despite my attempts in Product.vue as shown bel ...

Is there a way to deactivate both my input field and its associated content by choosing a specific option?

I have been searching for a solution to my problem without any success. I'm currently learning javascript and jquery, and I want to figure out how to disable the <input> and its data when the option "none" is selected. My first attempt involved ...

What is the reasoning behind the decision for the javascript void statement to assess an expression?

When it comes to the javascript void statement, it is designed to evaluate an expression and yield the value of undefined. The concept behind this functionality stems from the fact that the global variable undefined can be altered. However, one might wonde ...

JavaScript is having difficulty retrieving the property value

Whenever I click a checkbox, I encounter the error "Unable to get the value of the property 'checked'. object is null or undefined." The form I am working with has the name 'test', and my objective is to display additional input fields ...

Attempting to develop a filtering feature using ReactJS

Having some trouble with the if statement in my filter list function. Can't seem to figure out why it's not working properly. Here is the code snippet: filterList (event) { var updatedList = this.props.array; var filterText = this.stat ...

Using ReactJS to Retrieve Input Value from Prompt Box and Save to Database

I'm currently developing a MERN application and I need to allow users to edit the food name by clicking on the prompt box that pops up when they click the Edit button. The approach I was following can be found in this link: [https://stackoverflow.com ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

JustGage error: Unable to locate element with ID 0 in AngularJS

I developed a custom directive for the JustGage plugin, here is how it looks: function justGage() { return { restrict: 'E', replace: true, scope: { universalId: '@', ...

Express error handling lacking clarity

My application has a route dedicated to accepting file uploads: Here's a snippet from app.js ... var upload = require('./routes/upload'); ... app.use('/upload', upload); ... ... /* It is essential to start the application with ...

What are the best ways to transfer information between functional components in a React application?

When working with React, data exchange between class-based components can be done using states and props in the following way: App.js import Name from './Name'; import React, { Component } from 'react' export class App extends Compo ...

If the internet connection drops, I would like to show an alert notifying me about the status

Can someone provide guidance on how to display an alert message indicating loss of internet connection using AngularJS in my app? I am currently working with the AngularJS Express framework and APIs. When I encounter a situation where the internet connect ...

Can the selected week be highlighted along with the corresponding week number in a row?

Can we display the number of the week in a row along with the selected week, either in the toolbar or somewhere else? I attempted to utilize ToolbarComponent, but it overrides the entire header. However, I would like to keep it as is and just add informat ...

Obtaining binary data directly from a combination of buffers

When working with the nodeJS Buffer().toString('utf8'), I encountered the following: Content-Type: audio/x-ms-wma Content-Disposition: form-data; name=recordedAudio \r\n\r\n0&uf\u0011\u0000 My goal is to strip ...

Is there a way to properly validate the innerText of a multiline form field in SharePoint?

I'm facing an issue with a code snippet related to my problem. The output from console.log(field1[0].innerText); seems correct, but the if statement validation is always resulting in false. I've attempted various types of string validations like ...

Issue with Vue.js 2.0 transition not triggering on changing routes dynamically

I've encountered an issue where transitions are not firing on dynamic routes with parameters. For example, when navigating from /chapter/1 to /chapter/2, no transition occurs. However, when going from /chapter/1 to /profile/1, a transition does occur! ...

Updating Ember.js view after a PUT request with Node.js and Express

As someone who is new to working with Ember, I have set up a basic Ember application with a CRUD page. The issue I am facing is with refreshing the view or template of the CRUD page after sending a PUT request to a node API that uses MongoDB. Interestingl ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...