Using on() or once() for `open` event in MongooseJS

I've seen a bunch of different ways of actually setting up a MongoDB connection:

  1. I've seen some code where people don't use the open or error event
  2. mongoose.connection.on('open', callback());
  3. mongoose.connection.once('open', callback());

My take on it is:

  • If my app only connected to the database when it needs to use it, use (2)
  • If my app is constantly connected to the database ... it doesn't matter if I use (2) or (3)?

Which also raises the question, should my app maintain a persistent connection to the database (server and database running on same machine)?

Thanks for any help

You are correct that it doesn't matter if you use (2) or (3) when your application is constantly connected to the database.

As far as a persistent connection goes, the only cost of that is a tcp keepalive packet every once in a while. It's up to you to determine if the extra socket is worth not having to make a new connection for every call.