V
V
VadimKholodilo2020-10-04 09:21:18
Node.js
VadimKholodilo, 2020-10-04 09:21:18

How to correctly pass the database connection to the model?

Hello. I have an application which is written using the Express framework.
I don't want to query the database directly in the routes. Instead, I want to create classes that will hide implementation details (models). For example, the user model will have the following functions getById, authorize(login, password) and some others.
The question is how to pass the connection to this model so as not to open the connection on every request.
I see it like this:
const express = require('express);
var users = require('./models/users.js');
const dbDriver = require('dbdriver'); / For this question, which database I'm using doesn't matter
app = express();
dbDriver.connect(host, user, password).
users.init(connection); // Pass the connection object. The init function initializes an internal variable that holds the connection
app.users = users; // All routes will see this model via req.local.users
app,listen(3000);
}).catch(e) {
console.log('Unable to start API', e);
});

How would you do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-10-04
@VadimKholodilo

I would take a ready-made ORM, where everyone has already thought about this (sequelize for example) and not reinvent the wheel.
If you really want your bike? then your approach will work too.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question