My goal is to set up an express based api with node.js using mongodb version 4.0 and node.js driver 3.1.10.
At the current stage my part of the api is basically done but eventually my collegues will merge their progress on to it. So my question is:
How can I share my connection instance of mongodb to acces it across multiple methods?
My current structure is of this type:
- app.js server that calls route.js for routes managing
- route.js that calls userController.js for mangaing user conecerned methods
- userController.js that manages CRUD operations on resource /users
Searching on the web resulted that is recommended to keep a connection open so the nodejs driver will mange it for all queries, so what part of the connection I have to expose:
- the result of the
MongoClient.connect(url)callback? - the
MongoClient.connect(url)value itself?
And when and where I have to open the connection and do I have to close it?
I know that some similar questions exists but they are old and refer to mongodb api and javscript implementations that are old too, so with the use of callbacks or awaits how can I achieve this?