DEV Community

Rajesh T
Rajesh T

Posted on

1 1

Sharing single mongoDB connection object in Express Application

An appilcation may have multiple APIs. Now it is required to share single database object through out all APIs with out creating multiple collections.
First let us see the incorrect implementation
Ex:
app.get(‘/path1’,(req,res,next)=>{
MongoClient.connect(…………………….)
});
app.get(‘/path2’,(req,res,next)=>{
MongoClient.connect(…………………….)
})
Here two request handlers are creating their own connection whenever they execute.Multiple collection can effect the scaling of database.

Sharing the connection

There are a bunch of approaches that we can follow, and we'll discuss one that seems to be a really interesting one. We'll base our application on the fact that the API should not be available if the database is not available that powers it. This makes sense - there's no point in providing any endpoints if the database is down and we can't effectively display data.
To achieve this, we need to re-think our logic around connecting to the database a little bit - first, we should attempt to make the connection, and if that is successful, we can fire up the API server as well.

var MongoClient= require(“mongodb”).MongoClient;

MongoClient.connect(dbUrl,{useUnifiedTopology:true},(err,client)=>{
if(err){console.log("err in db con",err)}
else{
var dbo=client.db("b26db");
var usercollection=dbo.collection("usercollection");
var admincollection=dbo.collection("admincollection");
console.log("connected to db");
console.log(app.locals)

//assign the values to “locals” property of express object “app” 
    app.locals.usercollection=usercollection;
    app.locals.admincollection=admincollection;

    const port=3000;
Enter fullscreen mode Exit fullscreen mode

app.listen(port,()=>{ console.log(server listening on port ${port})});
}
});

app.locals object

The app.locals object has properties that are local variables within the application. Once set, the value of app.locals properties persist throughout the life of the application.
In the request handlers of api, we can access the data from “app.locals” property using “request” object.
someRouter.get( ‘/path’,(req , res , next )=>(
let usercollection=req.app.locals.usercollection;
…………………………………………
………………………………………..
)};

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (1)

Collapse
 
uthamgade profile image
uthamgade

This is a great idea sir. It saves lot of time. This is exactly what I am looking for.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️