CodexBloom - Programming Q&A Platform

Unhandled Promise Rejection in Node.js Express Service when Fetching Data from MongoDB

👀 Views: 54 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
node.js express mongoose JavaScript

I'm writing unit tests and I'm running into an scenario with my Node.js Express application where I'm attempting to fetch data from a MongoDB database using Mongoose. I have a simple GET route set up, but I'm working with an unhandled promise rejection behavior when the database call fails. Here's a snippet of my code: ```javascript const express = require('express'); const mongoose = require('mongoose'); const app = express(); // MongoDB connection mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true }); const Item = mongoose.model('Item', new mongoose.Schema({ name: String })); app.get('/items', async (req, res) => { try { const items = await Item.find(); res.json(items); } catch (behavior) { console.behavior('Database query failed:', behavior); res.status(500).send('Internal Server behavior'); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` When I run this code and the database is down, I get the following behavior in my console: ``` (node:1234) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect ``` I have tried wrapping the `await Item.find()` call in a try-catch block, but the behavior still bubbles up as an unhandled rejection. I've also checked my Mongoose version (5.12.3) and Node.js version (14.17.0) to ensure they are compatible. What can I do to properly handle cases where the database might not be reachable, and prevent this unhandled promise rejection? Is there a best practice for managing database connection errors in an Express app? For reference, this is a production mobile app. Any ideas what could be causing this? Cheers for any assistance!