Is there a mongoose connection error feedback

how can I set a callback to handle errors if mongoose cannot connect to my db?

I know

connection.on('open', function () { ... }); 

but there is something like

 connection.on('error', function (err) { ... }); 

?

+65
javascript mongodb mongoose
Jul 13 '11 at 9:00
source share
5 answers

When connecting, you may receive an error in the callback:

 mongoose.connect('mongodb://localhost/dbname', function(err) { if (err) throw err; }); 
+113
Jul 13 2018-11-11T00:
source share

there are many mongoose callbacks you can use,

 // CONNECTION EVENTS // When successfully connected mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + dbURI); }); // If the connection throws an error mongoose.connection.on('error',function (err) { console.log('Mongoose default connection error: ' + err); }); // When the connection is disconnected mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); // If the Node process ends, close the Mongoose connection process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose default connection disconnected through app termination'); process.exit(0); }); }); 

further: http://theholmesoffice.com/mongoose-connection-best-practice/

+38
Dec 05 '15 at 16:01
source share

In case someone happens to this, the version of Mongoose I am working with (3.4) works as indicated in the question. Therefore, the following may return an error.

 connection.on('error', function (err) { ... }); 
+21
Sep 01 '13 at 21:43
source share

Late answer, but if you want the server to work, you can use this:

 mongoose.connect('mongodb://localhost/dbname',function(err) { if (err) return console.error(err); }); 
+2
Jun 21 '15 at 19:00
source share

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.

+1
Aug 25 '19 at 22:09
source share



All Articles