Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "message" variable remains unchanged.

async function postRegister(req, res) {
  const familyName = req.body.familyName;
  const email = req.body.email;
  const password = req.body.password;
  const repeatPassword = req.body.repeatPassword;

  let message = 'msg';

  // Check if user already exists
  await db
    .promise()
    .query(
      'SELECT * FROM users WHERE email = ?',
      [email],
      function (err, results) {
        if (results.length > 1) {
          console.log('Inside first if');
          message = 'User already exists.';
          return;
        } else {
          if (password !== repeatPassword) {
            console.log('passwords do not match');
          } else {
            const newUser = new User(familyName, password, email);
            newUser.save();
            res.redirect('/login');
          }
        }
      }
    );
  console.log(message);
  res.render('authentication/register', { message: message });
}

Answer №1

Make sure to follow this advice: Instead of looking for all users, just search for one since there will be no duplicate entries.

  try {
    const user = await User.findOne({ email: email})

    let message = ''

    if(user) {
      message = 'User already exists'
      // It would be best to return the response at this point
    }

    if (password !== repeatPassword) {
      message 'passwords do not match'
    }

    if(message) {
      // If there is an error message present, take action here
    }

    // Proceed to create the new user
    res.redirect('/login')
  } catch(err) {
    console.log(err)
  }

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

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

How can the click event for a SubMenu in Ant Design be deactivated?

Is there a way to keep the SubMenu from toggling its child menus when clicked, without disabling it? I would like the SubMenu to maintain its appearance while preventing its children from expanding or collapsing. ...

Retrieve a text file using FTP asynchronously and utilizing Promises in Node.js and AWS Lambda

Utilizing a single Node module called basic-ftp, I am tasked with downloading a txt file in AWS Lambda and storing it in the /tmp/ directory within the Lambda function. The goal is to manipulate the txt file and its contents outside of the FTP function. ...

Header misalignment occurs when the user scrolls up too quickly causing it to display

One interesting feature on my website is that the header disappears as users scroll down the page, but reappears when they start scrolling back up, even if they are halfway down. However, if a user quickly scrolls up and down, there seems to be an issue wi ...

Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setIn ...

The NextJS API is throwing an error due to a mysterious column being referenced in

I am currently in the process of developing an API that is designed to extract data from a MySQL table based on a specific category. The code snippet below represents my current implementation: import { sql_query } from "../../../lib/db" export ...

Automate logging in and out of Gmail chat by programmatically simulating clicks on the span elements that represent the chat status in Gmail

When I'm at work, I prefer using Gmail's encrypted chat feature because it logs chats without saving anything to the hard drive. However, when I'm at home, I switch to Pidgin as logging into Gmail chat at home can lead to messages ending up ...

Struggling to enable Google Cast functionality on Apache Cordova: Unhandled error - chrome is not recognized

Struggling to integrate Google Cast with Apache Cordova, I'm facing challenges due to outdated guides and plugins. Despite finding a recently updated plugin three months ago, I keep encountering this error: Uncaught ReferenceError: chrome is not defi ...

What is the correct way to serve JSON files with appropriate MIME type and avoid using text/plain?

My attempts to utilize a manifest.json file have been unsuccessful due to it refusing to work unless the type is set to application/json. The setup includes an nginx server running node/express. I placed the manifest.json in the public folder, but the se ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Converting HTML and CSS into a PDF using JavaScript

I am on the lookout for libraries that can cater to my specific needs, as I haven't found one that fits perfectly yet. My setup involves Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support includes IE8 and up, chr ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

Step-by-step guide on activating a controller function following an Animation in Angular JS

I have hit a roadblock trying to connect a series of animations with a controller action. My goal is to: 1. click on a button/div, 2. Trigger an animation, 3. Once the animation finishes, execute a function in the controller to reset the button/div. I&a ...

How to reference a variable name within a JSON selector in AngularJS

I am working on a table using angularjs where I need to iterate through an array to display specific headers from a json object. The header displays correctly, but the issue arises when trying to utilize a variable from my nested ng-repeat as a json select ...

Utilizing dynamic data within the ng-template

As a newcomer to Angular, I am facing a challenge in passing a string into a template. My goal is to create a reusable template or component that can display instructions on how to proceed with an action. Currently, I am achieving this by using the follow ...

How to retrieve values from checkboxes generated dynamically in php using jquery

This is a unique question and not related to event binding or any suggested duplicates. Hello, I am facing an issue while trying to fetch the value of a checkbox to send it in an ajax request to a PHP page. The checkboxes are dynamically created using PHP ...

Easy task tracker in Vue.js

I’m currently delving into the world of VueJS and working on a simple to-do list application. The issue I’m facing is that I can't seem to successfully pass an array to the child component responsible for displaying the list: Parent Component < ...

Looping through data in AngularJS with duplicated entries

I'm having an issue with my AngularJS ng-repeat when trying to display JSON data. The records are duplicating, but only after reloading the page. Initially, everything works fine. Take a look at the JSON data below: [{ "EmployeeName": "Jishn ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...