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;
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;
…………………………………………
………………………………………..
)};
Top comments (1)
This is a great idea sir. It saves lot of time. This is exactly what I am looking for.