Connection events

The connection process in Mongoose inherits the Node EventEmitter class, meaning that we can set certain code to run following specific events. We can—and will—work with some of the connection events, such as connected, disconnected, and error.

The connection events are all used in the same way, sending a callback to the connection.on event listener. For example, if we wanted to log to the console when a connection error occurs we could do this in the following code:

mongoose.connection.on('error',function (err) {
  console.log('Mongoose connection error: ' + err);
});

Get Mongoose for Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.