Unable to locate information within MongoDB and employ the .then method

I am currently working on developing a simple authentication system. The data in my MongoDB database looks like this:

{
  "__v": 0,
  "password": "4c1b9bb3405f53cf46731af89f07b01d1ffe974f944d81085cb962abc45ee9c3",
  "_id": "589f5ee85a3b61176c9d0a61"
}

Below are the functions I have written to check this data:

router.post('/api/admin/login', (req, res) => {
    db.getRootToken(req.body).then(function(data) {
        if (data.error) {
            return res.status(403).send(data);
        } else {
            return res.status(200).send(data);
        }
    });
});

function getRootToken(data) {
    console.log(data.password);
    var password_sha256 = sha256(data.password);
    console.log(password_sha256);
    Root.findOne({ password: password_sha256 }, function(err, docs) {
        console.log(docs.length);
        if (docs.length) {
            console.log("root found");
            return { token: password_sha256 };
        } else {
            console.log("root not found");
            return { error: "Incorrect password!" };
        }
    });
}

However, when I try to use /api/admin/login with { "password" : "pa55word" }, I encounter this error:

TypeError: Cannot read property "then" of undefined

The application is unable to find any data because the code returns "root not found", even though the hash function generates

4c1b9bb3405f53cf46731af89f07b01d1ffe974f944d81085cb962abc45ee9c3
for "pa55word", which matches the value in the database.

I am looking for guidance on identifying and correcting these errors. Any help would be appreciated.

Answer №1

Resolved by implementing callback and utilizing find instead of findOne method. Appreciate the help!

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

Troubleshooting: Issue with selecting items in jQuery Datatables

While attempting to construct a jQuery datatable using a data object, I encountered an issue. The table is displayed correctly, but the selection feature within the datatable is not functioning as intended. My expectation was that when a row is selected, i ...

Retrieving an Object from an Object Group in javascript

I am encountering an issue while looping through something. https://i.sstatic.net/JkqcP.png However, I'm facing difficulties in obtaining the [["PromiseValue"]] object. If anyone can assist me with this, I would greatly appreciate it. Update : Th ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Resolving the 'Uncaught TypeError: number is not a function error' and tackling the 'Failed to load resource' issue

What is causing the error in the code? var images = ['/test/img/Gallery/large/4cba0c8a-4acc-4f4a-9d71-0a444afdf48d.jpg','/test/img/Gallery/large/4cba0ca8-2158-41af-829a-0a444afdf48d.jpg','/test/img/Gallery/large/4cbc549a-5228-433f ...

Enhance the efficiency of a MongoDB query incorporating a "$where" expression to boost performance

Need help optimizing a query for a MongoDB server: QUERY = { "$and" : [ {"x" : {'$gt' : 1.0}}, {"y" : {'$gt' : 0.1}}, {"$where" : 'this.s1.length < this.s2.leng ...

I am facing an issue with Ajax in Laravel, as it is displaying a page not

I'm having trouble sending OTP with Laravel and Ajax. Whenever I try to call the Ajax function, it displays an error saying "Page not found"... HTML: ` <div id="first_step"> <div class="col-md-4" ...

retrieve information stored as a JSON object

Below is the json object that I am working with: $dati = array( "data" => array( 'address_complete'=>$data->results[0]->formatted_address, 'address_square'=>$data->results[0]->address_component ...

How to Transfer a Props Value to an External Function in Vue 3

I'm currently working on a page that displays user details and need to also show the invoices associated with that user. <template> <div> <div> // Child component one ..... </div> <div ...

Is the height of $(element) equal to the clientHeight of the element?

Do these two elements have identical properties? In my experiments, it seems like they yield the same result. I'm currently working on enhancing my code by utilizing native JavaScript properties... ...

Imagine a scenario where clicking on an image causes it to be rotated or

Could use some assistance figuring out what's missing here. I've added a random photo from Wiki, similar in size to the images I'll be working with. The images will vary in size, but I want them to always remain visible within the browser w ...

Nodejs provides a platform for running continuous tasks in an efficient

I am currently using nodejs with express for my webapp and I have a requirement to continuously run some code that monitors data changes and updates my mongodb accordingly. How can I create a background process that runs alongside the main task, allowing ...

Is it possible to apply withStyles to the output of a function?

Currently, I am attempting to add extra styling to the output of a function that returns one of two components based on specific props. Here is an example: import React from 'react' import { withStyles } from '@material-ui/core/styles' ...

Combining objects within an array based on shared key values

Is there a way to merge objects with the same date into one cohesive data set? I could use some guidance. const info = [ { date: '1 Day', green: 35 }, { date: '2 Day', green: 64 }, { date ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

"Upon returning from a child component, the React component's method 'this.state.myState'

In my React code, I have a Parent component called BookApplication and a child component called SearchBox. The SearchBox contains an input field that should pass the input back to the parent component for event handling. The data flow seems to be working c ...

What is the best way to extract URL query parameters and store them in a MySQL database using Node.js and Express

I am working on a project where I need to store specific information like names and widths from the URL query into my MySQL database. The format of the URL query should resemble this: /register?name=XXXX&width=###.### However, I seem to be facing ch ...

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

Encountering issues while attempting to modify the route from a particular Component

I have encountered an issue with changing routes in React from a specific component to another. Switching between '/' and '/login' works fine, but when the active route is '/menu-management', clicking on the Link causes an err ...

I am in possession of a RIFF-encoded file. Could you please advise me on the procedure for sending this file via an ajax post response?

My goal is to maintain the RIFF encoding of the file when sending it as a response, like this: router.post('/someroute', function(req,res,next){ var riff1= fs.readFileSync(somefilepath); res.send(riff1); } After making an AJAX ...