Miha Šušteršič
Miha Šušteršič

Reputation: 10062

nodejs - mongoose not throwing an error with a broken Uri

I have the following code in my index.ts file:

import mongoose from 'mongoose'

const DBUri = "blah";

const connectDatabase = (): void => {
    try {
        mongoose.connect(DBUri, {useNewUrlParser: true}, () => {
            console.log('mongoose connected.')
        })
    } catch (e) {
        console.log(e);
        throw e
    }
};

connectDatabase()

When I compile into js and execute the file, I get mongoose connected logged into the console. But I would expect an error to be thrown (since the DBUri is broken).

What am I doing wrong?

Upvotes: 0

Views: 48

Answers (2)

Muhammad Ali
Muhammad Ali

Reputation: 2014

You will find you error or disconnection thru these events

try {
      mongoose.connect(DBUri, {useNewUrlParser: true}, () => {
          console.log('mongoose connected.')
      })

       mongoose.connection.on('disconnected', () => { console.log("Disconnect")  });

       mongoose.connection.on('error', (error) => {
       console.error('[error]: ', error);
      });
    } catch (e) {
    console.log(e);
    throw e
   }

Upvotes: 1

Älskar
Älskar

Reputation: 2577

You should be capturing an error argument in your callback as per the Mongoose documentation:

mongoose.connect(DBUri, {useNewUrlParser: true}, (err) => {
  if(err) return console.log('mongoose failed to connect.')
  console.log('mongoose connected.')
});

Additionally, your try..catch is superfluous since you are already passing error handling to Mongoose via that callback.

https://mongoosejs.com/docs/connections.html#callback

Upvotes: 0

Related Questions