Understanding the asynchronous behavior of Mongoose's findById method

I want to discuss the code I am currently working on:

const checkForRecord = async (id) => {

    let model = mongoose.model('User');

    let query = {}
    query.dummy = false; <== This particular field is causing an error intentionally, as it does not exist in my User model.
    let result = await model.findById(id, query);

    console.log('This part of the code is being reached !!!');
    console.log(result);
}

However, I encounter the following error:

(node:6680) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value ...

In addition, my console.log statements do not seem to execute.

Why is this error not being caught in the result variable, considering that my function is asynchronous?

I have tried both approaches:

let result = await model.findById(id, query);

and

let result = await model.findById(id, query).exec();

Yet, the outcome remains the same.

Answer №1

My console.logs are not getting executed at all.

This is the expected behavior. The function in question is asynchronous and it waits for a promise to be returned. In this scenario, rejections are treated as exceptions which cause the termination of the checkForRecord function.

Why isn't that error being assigned to result, considering my operation is async?

The reason is that the error is not a resolution value (which is what await provides); instead, it is a rejection or exception. Understanding the de-sugared version of checkForRecord by replacing async and await with their underlying promise operations may provide clarity:

// checkForRecord with async/await desugared to their underyling Promise operations
const checkForRecord = (id) => {

    let model = mongoose.model('User');

    let query = {};
    query.dummy = false; // <== To trigger an error, this field is not utilized
    return model.findById(id, query).then(value => {
        let result = value;
        console.log('Code reached here !!!');
        console.log(result);
    });
};

In the above code snippet, the console.log statements won't run because they're within a resolution handler. Rejections do not go to a resolution handler but to a rejection handler.

To clarify, there is no requirement to modify checkForRecord. The provided example demonstrates how async/await translates at runtime.

Your current implementation of checkForRecord is correct (except for missing => and absence of comments on the query.dummy line). You should utilize it as follows inside an async function:

try {
    checkForRecord(someId);
} catch (e) {
    // Handle the error here
}

Alternatively, if not within an async function, you can handle errors as shown below:

checkForRecord(someId).catch(e => {
    // Handle the error here
});

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 is the best way to determine the quantity of elements received from an ajax request?

Here's the method I am currently using to count the number of li elements returned from an AJAX call: $.post('@Url.Action("actionName", "controller")', function (data) { $('#notificationCounter').html($(data).find('li&a ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

Why is npm attempting to compile a previous version of my code?

Being a complete newbie to npm and node.js, I hope you can bear with me if I'm lacking in providing the right details. I am working on developing a plugin for a website that utilizes an out-of-the-box framework within npm. Initially, everything was ru ...

The system is unable to show real-time data at the moment due to an error message being returned: {"error": "'QuerySet' object has no attribute 'body'"}

I am looking to integrate real-time data display in a Django application using Ajax. My goal is to allow users to see what they are typing as they type it, and I am achieving this by utilizing Django's JsonResponse with the following method: def get_ ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

A technique to loop through a single property in multiple JSON Arrays within a response array

I received an array of responses from an HTTP Get request. The structure is as follows: https://i.sstatic.net/uqwAF.jpg I am trying to display the 'name' properties of each object in the array using *ngFor directive in Angular. I attempted the ...

The favicon fails to appear properly when sharing the link on Instagram

Whenever I share my website link on Instagram, it shows an image that is not the one I want to appear. Oddly enough, when I send the URL through a text message, the Favicon displays correctly. How can I resolve this problem? https://i.sstatic.net/siQVs.pn ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Tips on restricting users to choose dates that are later than the current date

Currently, I am working with Vue3 using the options API. After reviewing this StackBlitz, my question is regarding how to correctly set the :max value for a date-picker. Even though I have assigned :max as new Date(), I am still able to select dates that ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Refreshing the page in Next.js causes issues with the CSS classNames

I am currently in the process of migrating a React SPA to Next.js, and I am relatively new to this framework. The issue I am encountering is that when I initially load the Home page, everything appears as expected. However, if I refresh the page, incorrect ...

What could be causing this RangeError to constantly come up while I'm performing a basic math operation in node.js?

My program simply takes two inputs from an HTML form, parses them into text in Node, and then performs a math operation on the two. Strangely, this issue only occurs when dealing with numbers, not strings. Despite the error message indicating an invalid s ...

Guide to retrieving documents using an array of IDs, even if some IDs are duplicated in the array

Recently, I made an interesting discovery in mongoose where I can iterate find() without using a loop. Here is the method: const arrOfIds = reqBody.items.map(item => item.productId); Product.find({ '_id': { $in: arrOfIds }},(error, r ...

What is the best way to implement a never-ending scrolling grid loader within a scrollable area using Codeigniter?

In my Codeigniter framework and bootstrap installation, I have multiple sub-pages. On one of these pages, I am attempting to implement an infinite scroll loader using a jQuery script from a tutorial found at gridScrollFx.js. Here is the JS file I am using: ...

VSCode API alerts user when a rejected promise is left unhandled for more than a second

After working diligently on developing my first vscode extension, I encountered a roadblock when the debugger halted the execution of my extension. As a newcomer to JavaScript, I suspect that I may be overlooking something related to "thenables" that is c ...

Using ajax to send an array to PHP

I have an array named "heart" that is being sent via ajax... var heart = [31,32,33,34,35,36,37,38,39,42,43]; // Sending this data via ajax to php file/ $.ajax({ type: "POST", data:{ 'system': heart }, url: "login-function.php", success: f ...

Is it necessary to configure modules using app.use in every route in express.js?

I recently learned that it is best practice to include the express module individually in each route file, rather than globally in app.js. Now I'm questioning whether I need to duplicate all the app.use statements in each route file or if I can just ...

Encountered a snag while executing Powershell with Selenium: Error message - unable to interact with

Looking to update a textarea with a value? The script below triggers an error stating "element not interactable". This occurs because the textarea is set to "display:none". However, manually removing the "NONE" word allows the script to successfully set th ...

Is there a way to transfer the content of a div into a fresh window while retaining its original formatting

Here is a way to copy a new page: var yourDOCTYPE = "<!DOCTYPE html..."; // the doctype declaration var printPreview = window.open('about:blank', 'print_preview'); var printDocument = printPreview.document; printDocument.open(); pri ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...