What is the best way to retrieve the result of a find() operation in mongoDb?

In the process of creating a custom login page using mongoDb, I am utilizing an unofficial login system. This system involves express, session-express, and passport.

The core functionality is encapsulated in a file called 'passport-config.js'. This file contains validation logic to compare user information from the login form with the database.


import LocalStrategy from 'passport-local'
LocalStrategy.Strategy
import bcrypt from 'bcrypt' // for password encryption

function initialize(passport, getUserByEmail, getUserById) {
    const authenticateUser = async (email, password, done) => {
        const user = getUserByEmail(email) // retrieves user data based on email from login form

                // remaining code...
    }
    passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser)) //calls authenticateUser with form data
}

export default initialize

The function within 'passport-config.js' is exported and then imported into server.js. It requires parameters such as (passport, functions to find users by email and ID)

In server.js:


import initializePassaport from '../passport-config.js' // import the function from passport-config.js

import passport from 'passport'

import users from "../models/User.js"; // retrieve model Schema from users database

initializePassaport(
    passport,
    email =>  users.findOne({"email": email}, {}, (err, user) => user) // fetches user based on provided email
        id =>  users.findById(id, (err, user) => {email = user} => user) // fetches user based on ID
)


//more code...

An issue arises when passing parameters in 'server.js', instead of finding the user by email, it returns other values. This might be due to the value sent by the find() function in mongoDb being inaccessible outside the function.

A debug log was added: "email => users.findOne({"email": email}, {}, (err, user) => {console.log(user})". While it displays the correct value in the console, it doesn't pass the right value to the function.

Attempts were made to use return statements without success. Researching yielded no solutions to this problem.

Prior to integrating the database, the code worked flawlessly with a simple array:



const users = [ // example
    {
    "id": '167252944716', 
    "username": 'adm',
    "email": 'adm@adm', 
    "password": '$2b$12$G/EwhnXj5P/y1NGTb5Sq4.OTY5m.BMferVHVJ27AtZGn8vt6qDsvi' //encrypted
    }
]


initializePassaport(
    passport,
    email => users.find(user => user.email === email),
    id => users.find(user => user.id === id)
)


If unclear, please provide feedback for clarification purposes. Thank you!

Answer №1

When using findOne and findById in async functions, they return a promise that needs to be resolved either by using the await keyword or the .then() method. Here is an example of how you can handle this:

const checkUserCredentials = async (email, password, callback) => {
    try {
        const user = await fetchUserByEmail(email);
        const isPasswordMatch = await bcrypt.compare(password, user.password);
        if (isPasswordMatch) {
            return callback(null, user);
        } else {
            return callback(null, false, { message: 'Incorrect password' });
        }
    } catch (error) {
        return callback(error);
    }
};

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

Managing JWT Verification Errors

I am looking to update the JWT secret key without causing any browser errors for users who are already logged in. Currently, changing the JWT secret key while a user is logged in results in a browser error. The only solution is for the user to manually de ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

What is the best way to modify a single necessary attribute without altering any of the other mandatory properties?

Issue I am facing a challenge where I need to update a single property, such as `productPrice`, without affecting the other required properties. I want to be able to change any individual property independently. Whenever I try to update the value of `prod ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

Error Message: "Oops! It looks like you are trying to access a property or method

I am in the process of developing a static website that includes tabs (a reactive property), each containing multiple cards (also a reactive property) with images and text. Recently, I encountered the following warning: [Vue warn]: Property or method &qu ...

Django Implementation of JavaScript Confirmation Dialogue

Currently working on a Django form that requires a confirm/cancel dialog upon submission. I've considered sending POST data from jQuery, but I'm curious if it's possible to integrate a JavaScript dialog as middleware instead? ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

What is the best way for OnSubmit to access an external file?

Recently, I adjusted this code snippet to include the onsubmit attribute with a validation function call. Instead of having the validate function within the same file, I moved it to an external file for better organization. Now, I am wondering how do I e ...

Tips for avoiding the use of import statements in Typescript

log.ts contains the code below import {LOG} from './log' LOG.e("tag","error"); LOG.f("tag","error"); LOG.d("tag","error"); I am looking for IntelliSense support in my TS file without affecting the output javascript. I only want this in my Java ...

Issues encountered when using PUT requests in a react.js application

I've encountered an issue with a PUT request where, after editing one field and saving, all other values except the edited one become null. It seems to be related to the onChange() function, but I'm not entirely sure. Below is all the relevant co ...

When utilizing ng-repeat and invoking the function in the HTML, the JSON array values fail to transfer to the HTML form

What I am trying to achieve: https://i.sstatic.net/hbdbC.jpg I am facing issues with getting the desired dynamic form output. The values are not being displayed and the data is not passing from the JavaScript file to the html form. I have even tried usin ...

Encountering the issue of `error.toJSON() not being a function` when managing errors with Axios

Whenever I execute my code, an error message appears saying error.toJSON is not a function. What would be the best approach to handle this error more effectively? const installDependencies = async (BASE_URL, body) => { try { const headers = { ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

What is the best way to automatically log in a user in Django if they have closed the tab without logging out?

I'm currently working on a Django project that involves both backend (Django) and frontend (HTML, CSS, JS). Everything is functioning as expected in terms of features like login, registration, and logout. However, there's a common requirement whe ...

Populate the database with values when the button is clicked

Hello, I encountered an issue with my code where it is adding empty values to the database when attempting to enter input text values. I am using PHP and MySQL for this task. <html> <body> <input type="text" name="value" /> <input ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

Exploring the concept of finding the maximum value in an array using recursion in JavaScript

After some experimentation, I managed to create a function that uses recursion to find the maximum value in an array. const max = ([a,...rest]) => !rest.length || a > max(rest) ? a : max(rest); console.log(max([-3,3,19,61,99,22,55])); // 99 console ...

Customize PassportJS Callback and Disable Session

Can I create a custom callback and disable session usage? The documentation explains how to disable sessions and use custom callbacks separately, but how can I do both at the same time? app.get('/login', function(req, res, next) { passport.aut ...

Having issues with starting npm, can anyone assist me?

I encountered a problem today and tried using commands like npm install, but I couldn't find a solution. Can anyone help me out? The issue started when I pressed ctrl-c and then used npm start to reload the server, and that's when all these error ...

Integrating JsonResult with Ajax forms and javascript: A comprehensive guide

When working with MVC4, how can I handle the response from a JsonResult action in an Ajax form? Most tutorials focus on handling html responses (ActionResult), making it difficult to find examples for Json results. I understand that this question is not ...