My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

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.

https://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.");
    })
}