As we can see from more detailed documentation on error handling , since the connect () method returns Promise, the catch promise is an option to use with mongoose connection.
Thus, to handle the initial connection errors, you should use .catch() or try/catch with async/await .
Thus, we have two options:
Using the .catch() method:
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }). catch(error => console.error(error));
or using try / catch:
try { await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); } catch (error) { console.error(error); }
IMHO, I think using catch is a cleaner way.
coderade Aug 25 '19 at 22:09 2019-08-25 22:09
source share