Retrieving Response Data from a SQL Callback Function in Node.js

Currently, I am working on a node.js application that includes a registration function. Within this function, the challenge lies in verifying whether a username has already been taken or not. My issue arises from the fact that the SQL module in node only accepts a callback function, making it impossible to return any booleans directly.

Below is an excerpt of the code from my controller module:

async function createUser(req, res) {

        try {
            const salt = await bcrypt.genSalt();
            const hashedPassword = await bcrypt.hash(req.body.password, salt);
            const newUser = {
                userName: req.body.username,
                userPassword: hashedPassword
            };
            const userExists = model.checkIfUserExists(newUser.userName);
    
            if (userExists == false){
    
                // create new user
    
            } else {
    
                // Send json back "user already exists"
    
            }
             
            res.status(201).json(newUser);
    
        } catch {
            res.status(500);
        }
    
    }

And here is the snippet of code from the model:

function checkIfUserExists(Username){
    console.log("Checking if user exists");
    let sql = "SELECT * FROM users WHERE user_name = ?";

    db_conn.query(sql, Username, (err, result) => {
        
        if (err){
            throw  err;
        }

        console.log(result);

        if (result.length > 0){

            return true;
        } else {

            return false;
        }


    });

}

Unfortunately, the "checkIfUserExists" method does not provide a direct true or false value, resulting in the "userExists" variable being null.

I am seeking advice on how to overcome this issue and improve the elegance of the code. Any assistance in fixing this would be greatly appreciated. Thank you :)

Answer №1

If you want to improve the function checkIfUserExists, consider passing a callback or using promises. If you're already utilizing async/await, it might be beneficial to make the return of checkIfUserExists a promise.


function checkIfUserExists(Username) {
    return new Promise((resolve,reject) => {
        console.log("Checking if user exists");
        let sql = "select * from users where user_name = ?";

        db_conn.query(sql, Username, (err, result) => {
            if (err) {
                throw err;
            }
            console.log(result);
            if (result.length > 0) {
                resolve()
            } else {
                reject()
            }
        });
    })
}

To call this function in your code:


async function createUser(req, res) {
    try {
        const salt = await bcrypt.genSalt(); //standard ist 10
        const hashedPassword = await bcrypt.hash(req.body.password, salt);
        const newUser = {
            userName: req.body.username,
            userPassword: hashedPassword
        };
        await model.checkIfUserExists(newUser.userName).catch(() => {
            // Send json back "user already exists
        });
        // create user
        res.status(201).json(newUser);
    } catch {
        res.status(500);
    }
}

Answer №2

Make sure to double check your catch statement and don't forget to include the await keyword before calling

model.checkIfUserExists(newUser.userName)

async function createUser(req, res) {

    try {
        const salt = await bcrypt.genSalt(); //standard is 10
        const hashedPassword = await bcrypt.hash(req.body.password, salt);
        const newUser = {
            userName: req.body.username,
            userPassword: hashedPassword
        };
        const userExists = await model.checkIfUserExists(newUser.userName);

        if (!userExists){
            // code to create a new user goes here

        } else {
            // Send JSON response saying "User already exists"

        }
        res.status(201).json(newUser);

    } catch(ex) {
        res.status(500);
    }

}

Make sure to return a promise from this function:

function checkIfUserExists(Username){
  return new Promise((resolve, reject) => {
    console.log("Checking if user exists");
    let sql = "select * from users where user_name = ?";

    db_conn.query(sql, Username, (err, result) => {

        if (err){
            return reject(err);
        }
        console.log(result);

        if (result.length > 0){
            return resolve(true);
        } else {
            return resolve(false);
        }

    });
  })
}

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

Challenges with removing jwt token cookie in Express

//token creation res.cookie('jwt', token, { httpOnly: true, maxAge : 60 * 60 * 24}); //logout and destroying the token exports.logout = (req, res) => { res.cookie('jwt', "token", {httpOnly:true,maxAge:1000}) //unfo ...

the architecture of multi-tenancy using Node.js and Sequelize

Currently, I am designing a multi-tenant application using nodejs and sequelize with the MySQL dialect. The plan is to have a single application that connects to multiple databases, each designated for a specific client. After authentication (using passp ...

Utilizing a backup system to store environment variables within a configuration file

Currently, I am utilizing my environment variables by directly referencing process.env.NODE_ENV throughout my application. While this method works, it is becoming challenging to manage and keep track of. Therefore, I would like to consolidate all these var ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Having trouble sending an image through a cloud-message Firebase notification

I have successfully incorporated notifications into my app, but I am facing an issue when trying to include an image in the notification. Below is my code implementation: notification(user.fcmToken, { notification: { title: title, body: me ...

What steps are involved in constructing Jodit from scratch?

Seeking a non-minified, readable version of Jodit, I attempted to build it myself. However, my lack of experience with composer, node, npm, webpack, TypeScript, and other tools has left me struggling. Is there anyone who can guide me through the process s ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

The perplexing simplicity of closure

Currently, I am endeavoring to enhance my knowledge of JavaScript closures. Let's consider the following two scenarios in Node.js: function A(){ console.log(data); //this will result in a null pointer } module.exports = function(data){ re ...

How can one effectively extract data from a database in a React application?

We have a basic react app with authorization, utilizing JWT tokens and Redux for state management. Personally, I find the code quite complex and obfuscated, making it challenging to grasp fully. However, let's set that aside. Upon login, a token is s ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

"Discovering an issue where a search query returns empty results in nodejs and mongodb when parameters are utilized in the

Searching for users in close proximity with specific criteria, I can't seem to get the desired results when using field1=No and field2=No (which is what cat represents as field2). The query returns empty. function (currentLoc, radius, cat, db, callba ...

Error Message: Module not found while using Node Express with TypeScriptIssue: A

I have set up a straightforward node express app using TypeScript. My goal is to implement an errorMiddleware in the index.ts file. As I try to start the server, I encounter the following error: at Module.require (node:internal/modules/cjs/loader:100 ...

Leveraging webpack for CSS bundling

I'm currently working on bundling some NPM modules using webpack instead of utilizing a CDN. While I've successfully managed to integrate the .js files, I'm facing challenges with including the .css files for these modules. One example is ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

How can we log user data to the console in a Node.js server's GET request response?

In order to create a basic Node server, the objective is to set up a GET request that delivers a response of "Hello World" and simultaneously logs any user data in the console. ...

Adding Data and Computing Totals in Mongoose

My database consists of two Mongoose models: one for transactions and the other for the tags associated with them. I am looking to generate reports using aggregate code similar to this: Transaction.aggregate([ { $unwind: '$tags' }, { $gr ...

HapiJS commences an extended duration background process

Is there a way to achieve the functionality of a PHP exec function in HapiJS? I have a scenario where the user submits a processing job that requires running in the background for a significant amount of time. An essential requirement is to provide the us ...

The Design of DynamoDB Applications

Utilizing DynamoDB in conjunction with node.js and Express for developing REST APIs has been a beneficial choice for us. We have opted for Dynamo on the backend due to its operational simplicity. To streamline our usage of DynamoDB, we have incorporated t ...

Express error handler failed to catch the validation error

I have a field type in my mongoose schema that is required. I've implemented a custom error handler in express like this: const notFound = (req, res, next) => { const error = new Error(`Not found-${req.originalUrl}`); res.status(404); next(er ...

Calculate age in years and months using a PHP timestamp

Currently, I am executing the following SQL script: SELECT TIMESTAMPDIFF(YEAR,CONCAT(dob_year, '-', dob_month, '-', dob_day),CURDATE()) as age FROM members This query is used to calculate the ages of users based on a timestam ...