Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question