Sign in
Log inSign up

Connection to database. How to connect?

Yashu Mittal's photo
Yashu Mittal
·Jul 27, 2020·

1 min read

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.

example.com/api/posts

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.");
    })
}
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct