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

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

What could be the reason for REQ.BODY being consistently devoid of any

I understand that there are already several solutions marked as working, but I am struggling to get it to work in my specific case. Please refrain from marking it as answered. Here is the scenario I'm facing: AJAX CLIENT-SIDE var data ={}; data.test ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

Steps to Incorporate jQuery Function in a Partial View Inside a Modal

My jquery button click method is functioning correctly in views outside of modals, but the uploadbtn button click method does not work when a partial view is loaded in the modals. <script src="~/lib/jquery/dist/jquery.min.js"></script> ...

Tips for making a multi-dimensional array using jQuery

Is it possible to generate a jQuery layout by using two separate each statements as shown below? arrar [ 'aaa'=>'ccsdfccc', 'bb'=>'aaddsaaaa', '1'=>[ 'three'=>'sdsds& ...

How to nullify the valueChanges pipe in Angular RxJS until the observable is resolved

A challenge I am facing is piping the valueChanges from a select element to trigger the appropriate API request and displaying a spinner until the response is received. Additionally, I am trying to utilize publish() and refCount() methods so that I can use ...

Can you share any recommendations or instances of modifying data within HTML tables using Laravel?

Has anyone ever needed to directly edit and update data in a HTML table using Laravel? I have successfully created "create" tables for different tasks, but I'm interested in being able to modify the data directly on an "index" page. While there are ...

What is the solution for the error "Firebase limitToLast is undefined"?

How can I restrict the number of items returned when watching the 'value' in my Firebase database? I keep getting an undefined error when using orderByChild on my Firebase reference. $scope.watchRef = new Firebase(ActiveFirebase.getBaseURL() ...

Is there a method for enabling GPT-3's "davinci" to engage in conversation with users via a bot on Discord by utilizing discord.js?

var collector = new MessageCollector(message.channel, filter, { max: 10, time: 60000, }) start_sequence = "\nAI: " retart_sequence = "\nHuman: " collector.on("collect", (msg) => { ...

Error sound produced when detecting KeyCode on the keyboard

I'm currently working on a JavaScript project that involves capturing keyboard input. However, I'm encountering an issue where every time the user presses a key, it triggers an error sound. Is there a way to disable this sound? ...

Setting a Javascript value to a Controller variable within an ASP.NET MVC View

I am trying to set the javascript variable contentArea to match content.Contents in my controller. How can this be accomplished? <script language="javascript" type="text/javascript"> $("#btnTest").click(function () { var content ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...

Trouble with CSS and JS tabs not activating when clicked?

I am experiencing issues with a navigation (organized in tabs) that is not functioning on this page, but it works correctly on this page using the same method for inclusion. When clicking "Norway" on the top left, the navigation opens but switching to the ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

Ensuring Accessibility in Vue using Jest-Axe: It is important for buttons to have clear and distinguishable text. Is there a way to include a button name or aria-label when the content is passed through a slot

I have been focusing on enhancing the accessibility of my project by incorporating ESLint rules from vuejs-accessibility and integrating Jest-Axe. During the accessibility tests for my button components, Jest-Axe highlighted that Buttons must have discern ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...