1

In my code, I've used mongoose to establish a mongodb url connection. To avoid "DeprecationWarning", I've set "useNewUrlParser", "useUnifiedTopology", "useFindAndModify", "useCreateIndex" to true.

But, this avoids the catch block error. For example: If I put the wrong credentials in my atlas url, then this code doesn't show the error in the console.

const url = require('./setup/myUrl').mongoUrl

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose
    .connect(url)
    .then(() => console.log('DB is connected...'))
    .catch(err => console.log(`Error: ${err}`));  

1 Answer 1

1

@Mehedi Hasan The catch block handles initial connection errors only, to handle the errors that occurred from the DB you need to register db.on('error', () => {}); event.

For example:

mongoose.connect(dbPath, {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
}).catch((err) => {
    console.error(err.message); //Handles initial connection errors
    process.exit(1); // Exit process with failure
});

const db = mongoose.connection;
db.on('error', () => {
    console.log('> error occurred from the database');
});
db.once('open', () => {
    console.log('> successfully opened the database');
});
module.exports = mongoose;

Not the answer you're looking for? Browse other questions tagged or ask your own question.