gyula
gyula

Reputation: 267

Is it good practice to connect to the db multiple times?

I am using MongoDB, so I am connecting trough MongoClient.connect but I have to use that, for every route where I want to work with the database.

Tried to preload it to an object, but then the changes are not visible, till the server is restarted. Right now, it's working properly, I am only a bit worried about the performance.

Is there a better way to do that?

Upvotes: 1

Views: 684

Answers (2)

paulsm4
paulsm4

Reputation: 121599

THe correct answer is "it depends".

For a simple desktop application where your NodeJS program is the only client: sure. A persistent connection is fine.

For an enterprise application with 100s or 1000s of concurrent users each connecting independently: no, you probably do NOT want to hold the connection open "forever".

One possible solution for the latter scenario is Connection Pooling.

Upvotes: 1

AJ Funk
AJ Funk

Reputation: 3187

You should only need to connect to your DB once - when the server starts. As long as the server is running, the connection should persist. There is no reason to connect multiple times.

Upvotes: 2

Related Questions