简体   繁体   中英

MongoClient on error event

I am using Node/Mongo and want to capture all MongoErrors so that I can transform then into another error format. I am looking to do this at the base level but cannot figure it out.

Here's my connection setup:

let connection = false

// Create a Mongo connection
export function getConnection () {
  if (!connection) {
    connection = MongoClient.connect(config.db.mongo.uri, {
      promiseLibrary: Promise //Bluebird
    })
  }

  return connection
}

// Fetch a connection for a collection
export function getCollection (collection) {
  return getConnection().then(c =>
     c.collection(collection)
  )
}

I've tried adding on('error') to both connection and MongoClient as well as MongoClient.Db but they do not have that method. I've additionally added a catch block to my getCollection but the errors do not seem to hit it (I am testing with the MongoError 11000 for duplicate fields.

It seems that it can be done but haven't figured it out. It may be because I am using promises.

This snippet of code does it for us. I suspect you need to pass in the function that handles the 'error' event as well. Hope it helps someone who stumbles across this question in the future.

MongoClient.connect(database_string, (err, db) => {
  this.db.on('error', function() {
  console.error("Lost connection to mongodb(error), exiting".bold.red);
  return process.exit(1);
}); // deal breaker for now
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM