mongodb-developer / nodejs-quickstart

This repository contains code samples for the Node.js Quick Start blog post series

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

One connection for each model?

yhojann-cl opened this issue · comments

Is it normal for each entity to have its own connection to the database? if I have 30 objects will I have 30 connections persistently?

Is it normal for each entity to have its own connection to the database? if I have 30 objects will I have 30 connections persistently?

It's just a quick start you can have one connection made and exported the client through which you can access the db on different code-blocks...

It may be a quick start but I have seen many people follow the examples and make a connection for each data model, creating bad practice. I suggest that the examples live up to a real scenario without ceasing to be short examples, for example making a global declaration and sending the handler to the data layers, for example, through an additional variable in the constructor.

Thanks for the feedback! I'll take this into consideration the next time I update the code and article series.

What you'll want to do is create an instance of MongoClient when your app starts and then use that client throughout your app.

Yes, I would appreciate it very much and avoid many bad practices of those who are just starting to use mongodb and use these examples as true bases.

What you'll want to do is create an instance of MongoClient when your app starts and then use that client throughout your app.

Although, how would you handle the case if the mongo connection dies in between the whole course of the application?

What you'll want to do is create an instance of MongoClient when your app starts and then use that client throughout your app.

Although, how would you handle the case if the mongo connection dies in between the whole course of the application?

Related: https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application/14464750#14464750

But:

This is the correct answer. The accepted answer is very wrong as it says to open a connection pool for each request and then close it after doing so. Terrible architecture.

Although, how would you handle the case if the mongo connection dies in between the whole course of the application?

Without writing the code myself, I'm having trouble visualizing the flow. This is a good question to ask in the Community: community.mongodb.com.

Look at this piece of code - this works well for me. I've been using it in a production application for some time. I use only one connection throughout the app.

Look at this piece of code - this works well for me. I've been using it in a production application for some time. I use only one connection throughout the app.

Thanks man, this seems to work great.