Searching for an individual MongoDB document using Express

I recently started working with MongoDB and express. I am trying to authenticate a user based on their username and password, but my code seems to always execute the "else statement" even when the correct credentials are entered.

Below is the JavaScript file snippet:

    app.post('/auth', function(req, res){

    var user = ( db.collection('auth').findOne({name: req.body.username}));
    var pass = ( db.collection('auth').findOne({password: req.body.password}));

    if(user == req.body.username && pass == req.body.password){
        res.send("Credentials Match");
    }else{
        res.send("Wrong Credentials");
    }
    console.log(req.body);
})

And here is the HTML code snippet:

 <form class="form-signin" action="/auth" method="POST">
        <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
        <label for="inputEmail" class="sr-only">Username</label>
        <input type="text" placeholder="Username" name="username" required="">
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="password" placeholder="password" required="">
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
 </form>

Answer №1

These two lines of code illustrate an asynchronous operation:

var user = ( db.collection('auth').findOne({name: req.body.username}));
var pass = ( db.collection('auth').findOne({password: req.body.password}));

Because of the asynchronous nature, the if else statements will not wait for their execution.

Unless you explicitly command JavaScript to wait.

You can achieve this by using async/await to ensure that the code pauses until the asynchronous tasks are completed.

Additonally, fetching the username and password separately may lead to a security vulnerability.

If a user enters the correct name but a different password found in the database, it would still allow access when it shouldn't.

To avoid this issue, make sure to retrieve both the username and password from the same document.

An updated solution could look like this:

app.post('/auth', async function(req, res) { // note the async keyword here
    try {
        var user = await db.collection('auth').findOne({ name: req.body.username , password: req.body.password });

        if (user && user.name == req.body.username && user.password == req.body.password) {
            res.send("Credentials Match");
        } else {
            res.send("Wrong Credentials");
        }
        console.log(req.body);
    }
    catch (err) {
        console.log('Exception >>\n', err); // log the error
        res.send("Something wrong has happened while checking the credentials");
    }
})

I hope this explanation helps!

Answer №2

When using the findOne method, it is important to note that it returns a document rather than a string. This means that comparing it with a string may result in failure. To successfully compare, you need to retrieve the document first.

var user = db.collection('auth').findOne({name: req.body.username, password: req.body.password});

Once you have retrieved the user with the desired name and password combination, you can check if the user is null or an actual document to determine your if/else condition.

I recommend logging the current values of var user and var password using console.log() to identify any mistakes. Then, test the provided code snippet and observe any changes. Experiment with entering a "wrong" password to understand the return type difference and adjust your conditions accordingly.

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

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource (function(window) { function smp(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; i ...

What is the best way to change an int32 to a float32 in Deeplearn.js?

In December 2017, this code did the job perfectly. However, after updating Deeplearn.js to the latest version, it no longer functions as expected: math.scope(function(keep, track) { var i = track(dl.Array3D.fromPixels(rawImageData, 4)); i = math.multi ...

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User. The & ...

The functionality of Vue slot-scope seems to be restricted when used within nested child components

Here is the component configuration being discussed: Vue.component('myComponent', { data () { return { msg: 'Hello', } }, template: ` <div class="my-component"> <slot :ms ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...

Authentication Error: PassportJS Method not Found

Encountering a problem while trying to access passport functions from a separate config file. It seems like passport is not exposed when the file is required in routes. The error occurs at .post(passportConfig.authenticate('local-login', { Error ...

The PHP random number generator appears to be malfunctioning when being compared to the $_POST[] variable

In this section, random numbers are generated and converted to strings. These string values are then used in the HTML. $num1 = mt_rand(1, 9); $num2 = mt_rand(1, 9); $sum = $num1 + $num2; $str1 = (string) $num1; $str2 = (string) $num2; The following code ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

Fade in and out a Div with a distinct class and ID

I'm currently experiencing a minor issue with some jQuery code. Below are some divs: <div class="add" id="1">Follow</div> <div class="added" id="1">Following</div> <div class="add" id="2">Follow</div> <div clas ...

Storing ng-change event for a checkbox in AngularJS in a valid manner

I have a requirement where I need to handle multiple input checkboxes. The goal is to store the changed checkbox events in an array and then save them when the user submits the changes. <td><input type="checkbox" class="switch" ng-model="each_val ...

What's the reason behind the failure of bitwise xor within a JavaScript if statement?

I'm trying to understand the behavior of this code. Can anyone explain it? Link to Code function checkSignsWeird(a,b){ var output = ""; if(a^b < 0){ output = "The "+a+" and "+b+" have DIFFERENT signs."; }else{ output = ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Dynamic Data Causes Highcharts Date Formatting to Adapt

I wanted to create a line graph using Highcharts with the Date Format on x-axis set to "%b %e". For example, I expected 06/27/2014 to be displayed as Jun 17. Despite setting the date-format correctly, Highcharts seems to automatically change it when rende ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Amazon Lex: Transforming Speech to Text with Audio Technology

Is there a JavaScript SDK provided by Amazon for converting audio files to text using Amazon Lex? I am currently working on a Node.js application and would like to achieve this functionality. ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...