Should I start my database connection on server start?
Hello, quick question, I'm working on my back-end code for my product page website. My question is when connecting with my database (mongoDB in this case), I was wondering, as soon as the server starts, should we connect the database and then we just add functions to query it when needed Or we implement a connection string in each function.
That is for example, consider this code:
The connection happens in the function itself, my concern is should I write something like that or when server starts, run connectDB function then import it when needed to access my database settings?
7 Replies
Just came across that, any idea why it's more suitable to reuse our client, that is I guess I only need to have a function that runs that connect my database from start?
Because under the hood
MongoClient keeps a pool of connections. It's not just one connection, it's your gateway to multiple connections. This way it can send different requests to different connections and if one connection dies it can spawn a new one without stopping any in-flight connections or grinding all new connections to a halt.oh ok I see
so when we write something like
const client = new MongoClient(), under the hood, it's not a single connection being created (I thought it was) but rather it's a pool?Most DB ORMs use connection pools yeah
yup, thanks for the insight !
by the way
when we re use the client, we don't expect to have some
finally block that would close the client?You'll have to consult the docs for your ORM to find that out
noted, ty !