How can I resolve the error when Model.findOne() does not support a callback anymore?

I am facing an issue with this code as it is returning the error "Model.findOne() no longer accepts a callback". I need to resolve this issue without downgrading my mongoose version.

`router.post('/login', async(req, res) => {

const email = req.body.email;
const password = req.body.password;
const userType = req.body.userType;

let userSchema;
let redirectUrl;

// Determine the user schema and redirect URL based on the user type
if (userType === 'customer') {
    userSchema = Customers;
    redirectUrl = '/customer/home';
} else if (userType === 'hotel_owner') {
    userSchema = HotelOwners;
    redirectUrl = '/hotel_owner/home';
} else if (userType === 'advertiser') {
    userSchema = Advertisers;
    redirectUrl = '/advertiser/home';
} else if (userType === 'destination_manager') {
    userSchema = DestinationManagers;
    redirectUrl = '/destination_manager/home';
} else if (userType === 'admin') {
    userSchema = Admin;
    redirectUrl = '/admin/home';
}

// Search for the user in the respective schema
await userSchema.find({ email: email, password: password })
    .then(user => {
        if (!user) {
            // Return an error message if user is not found
            res.status(401).send({
                message: "Invalid email or password"
            });
        } else {
            // Redirect the user to their home page
            res.redirect(redirectUrl);
        }
    })
    .catch(err => {
        // Handle any errors
        console.error(err);
        res.status(500).send({
            message: "An error occurred"
        });
    });

});`

Can someone help me in fixing this error to make the code work properly?

Answer №1

When already utilizing await, consider the following approach:

try {
    const person = await personSchema.findOne({email, password})
    if (!person) {
        //In case of no matching person, take action...
    }
    // When a person is found, proceed with the following steps...
} catch (error) {
    //Manage any errors occurring during the process
}

Furthermore, remember to use a model rather than a schema for executing functions like find()

const Person = mongoose.model("Person", personSchema)
const people = Person.find() // Or similar actions

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

What methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Navbar active class not updating on jQuery page scroll

My one-page website has a fixed navbar that I want to change its active status when scrolling down to specific div positions. Even though I tried using jQuery, the code doesn't seem to work as intended. Here is the snippet: // SMOOTH SCROLLING PAGES ...

Is there a way to extract the text from the inner div of an element using nightwatch.js?

I'm attempting to retrieve the content of a cell within a table, with the following CSS structure: <div data-testid="cellvalue_row-1_col-0" class="Table-cellContent" xpath="1"><span data-testid="tableCellCon ...

Following the same occurrence using varying mouse clicks

I am currently exploring the most effective method for tracking file downloads (specifically, pdf files) on my website using Google Analytics (UA). I understand that by utilizing <a href="book.pdf" onClick="ga('send','event','P ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

What is the best way to pass a value back to the main function from an async.eachOfSeries function?

Currently, I am utilizing the async npm library in my project. I am interested in finding a way to return the value of 'someVar' back to the main function. The documentation indicates that it returns a promise if a callback is not provided. Howe ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Ensure the appropriate TypeScript types are utilized for error middleware in Express

Struggling to properly define the types in my express application. I am encountering issues with my middleware error function and cannot seem to find a suitable example or get the correct types set up. Despite numerous attempts, here is my current version: ...

Angular event triggered when updating input values from the model

I have developed a custom directive to add functionality to input fields with a specific class. I want to trigger events on blur and focus to update the label style based on Material Design principles. However, when using ng-model in Angular, I also need t ...

Is FIREFOX better with plugins or extensions?

I have created a JavaScript function that changes the colors of images on web pages, specifically to assist colorblind individuals in identifying content. The entire development process was done using JavaScript within the Dreamweaver environment, along w ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

Techniques for triggering JavaScript on elements that have been dynamically loaded via Ajax

When it comes to ensuring that a certain functionality works both when the document is ready and after an Ajax call, there are some considerations to keep in mind for optimal performance. An approach I found effective involves defining the desired code wi ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

Troubleshooting iFrame Loading Issues with HTML5 PostMessage

Our code is utilizing the newest postMessage feature in HTML 5 to address cross-domain communication challenges. The issue I am facing is figuring out how to determine if the messages posted to an iFrame have been successfully loaded. If the frame fails to ...

In Node.js and Express, it is important to note that a variable must be declared before

When I use the express action get('items'), I encounter an issue while trying to call an external JSON-API and display the API response in my local response. The error that I am currently facing states that the items variable is not defined with ...

Exploring the capabilities of bodyParser.text() in an Express application using EJS

I have a project in progress for creating a search engine application using Express to query the Twitter API v1.1. In my current stage, I am facing an issue with submitting the search string to my server by parsing form data utilizing the bodyParser module ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Updating Text in Backbone.js Event

Is there a way to activate a change event on a text box within a backbone view? I attempted the following: events: { "onChanged input.autocomplete": "update" } The update fu ...