Handling Errors in MongoDB and Express

Issue

I have a Node/Express server communicating with MongoDB. Below is my initial function which I call whenever I want data from the database:

const withDB = async (operations, res) => {
    try {
        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('database-name');
        await operations(db);
        client.close();
    } catch (error) {
        res.status(500).json({ message: 'Error connecting to db', error });
    }
}

When I want to fetch, add, or edit some data I use:

app.get('/api/employees', async (req, res) => {
    withDB(async (db) => {        
        const tabInfo = await db.collection('users').find().toArray()
        res.status(200).json(tabInfo);
    }, res);
});

I have several of these operations performing CRUD operations, and all work fine, but for some reason this particular one above is causing an intermittent error:

res.status(500).json({
                ^
TypeError: Cannot read properties of undefined (reading 'status')

I haven’t yet been able to isolate when this error occurs? That fetch request is only called on one page of my React app, and I can’t make the server crash.

Does anyone have any suggestions as to how I can handle the error correctly to prevent the server crashing, or a system to automatically restart the server when it does?

Solution

So I finally worked out:

  1. Why the app was crashing
  2. How to stop it crashing
  3. How to restart it if it did crash

The app was crashing because it was being overloaded with requests. We eventually traced that the crashes were happening at the busiest times of the day. I initially just set out to implement PM2 to auto-restart the app, but in the process of implementing it, I discovered that the app (which is relatively lightweight) was crashing because I was using babel-node in production (which is not recommended)

I stopped the app from using so much resource by reconfiguring the production following these instructions. I also encountered an issue with some dependencies not being present, specifically regeneratorRuntime. Helpful (short) article found here resolved that. A great side-benefit is that my app is noticeably faster and more responsive.

Finally, I used PM2 to monitor and handle the app in production, including automatic restarts and all that good stuff. Once I’d set up the above, the quick start on the PM2 website worked flawlessly.

All in all, a helpful process which gives me a lot more confidence when deploying apps in a live environment in the future.

Answered By – Nathan Field

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published