What is the best way to connect to database from backend?
Should we connect at the root of the app inside app.js?
database.connect().then(response => {
console.log("Connected to database.");
app.listen(8080);
}).catch(error => {
console.log("Error connecting to database.");
})
Or, individual connection to each api call.
const getPosts = (res, req, next) => {
database.connect().then(response => {
console.log("Connected to database.");
console.log("Getting all posts.")
}).catch(error => {
console.log("Error connecting to database.");
})
}
Yashu Mittal
Full Stack Dev
Francesco Borrelli
Cloud Software Engineer and Pizza Lover
Imho, just to bring here some design pattern recall, have a single instance of the database connection object is the best practice (I'm broadly refering to the Singleton Pattern FYI). Like this you do not have to instanciate the db object and create the connection for each api call. You will save time and resource usage.