Search code examples
mongodbconnection

Mongo DB - UnhandledPromiseRejectionWarning: Error


I am testing my app on localhost and using mongdb to connect to a database. I was receiving this error: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:27017

I figured out how to reconnect by going into Services and manually starting MongoDB.

However, after researching, I found that my code is not handling the error catching properly. I am not sure how to restructure my code (using .catch() I believe?) to fix this.

Would appreciate any suggestions to help fix and will be great to be able to learn how to do so. Thanks in advance!

const express = require('express');
const validate = require('./validate.js');
const mongoose = require('mongoose');
const moviesRouter = require('./routes/movies.js');
const app = express();
const PORT = process.env.PORT || 3000;
const DATABASE_URL = process.env.DATABASE_URL || 
'mongodb://localhost/movies';


mongoose.connect(DATABASE_URL, { useNewUrlParser: true, 
useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', error => console.error(error));
db.once('open', () => console.log('Connected to Database'));

app.use(express.json());
app.use('/movies', moviesRouter);


app.listen(PORT,  () => console.log(`listening on port: ${PORT}`));

Solution

  • As you suggest, using a catch statement would be one way to handle the connection error:

    mongoose.connect(DATABASE_URL, { useNewUrlParser: true, 
    useUnifiedTopology: true }).catch(error => console.error(error));
    

    If an error happens during connection the error will be handled and returned. More info here: https://mongoosejs.com/docs/connections.html#error-handling