L
L
Lynatik0012020-07-24 17:47:10
Node.js
Lynatik001, 2020-07-24 17:47:10

Proper organization of connection to the database in NodeJS?

I still have an unfinished Telegramm bot on NodeJS. Here I try to do everything more or less competently. A question arose despite the fact that I realized that apparently I didn’t do the logic of connecting to the database correctly.

I have a db.js file - in it in the constructor there is a connection to the database. But I connect and create a database object in each controller (which is created for each schema model (bd)) - a kind of MVC.
As you understand, there will be many connections with this approach.
Then it may be easier to write to the session (Telegraf) what will be available on all scenes for the client. Or can eat what other ways on easier - easier?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
McBernar, 2020-07-24
@Lynatik001

Yes, you can use Sequelize and forget about manual management of the database and queries, or throw the database object into those modules that use it.

M
Megum1n, 2020-07-24
@Megum1n

Try to make a DB class, which will describe all the methods of working with the database (connection, disconnection, addition, update, etc.), and then create an object that you will import into all controllers.
Connect and disconnect the base in each method.
For example, there will be a call like: which does: 1. Connect to the server 2. Add an argument to the database 3. Disconnect from the server
database.add("test")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question