4

I am developing a Node.js application. It is made up of two modules: the first one with all the main operations, and the second one (which is an helper module) where I store the CRUD operations for my MongoDB database. On the first module I call the second module methods (e.g. second-module-method inside first-module-method).

When should I open and close the connection in the helper module? Should I either call MongoClient.connect() and db.close() in each method or connect to the database at the top of the .js file and never close the connection (or do anything else)?

My application may never stop running (or stop just for a few time). So should I just open the connection and never close it?

Community
  • 1
  • 1
Salvatore
  • 499
  • 10
  • 16
  • I think it's better to open the connection and do not close it. 1) You avoid running time connection fail. 2) You know instantly if the database is unreachable and so do something. 3) It's quicker to use an opened connection than creating one for your first requests. – Orelsanpls Aug 28 '17 at 13:45
  • Thank you @GrégoryNEUT but where should I connect to the database, inside each method or at the top of the .js file? – Salvatore Aug 28 '17 at 16:21
  • Should I make a connection pooling? – Salvatore Aug 29 '17 at 13:52
  • At the top of the .js file, and it will make the connection pooling by itself. You can change the pooling time and reconnection setting through options – Orelsanpls Aug 29 '17 at 13:59

0 Answers0