Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Access same instance of db connection in different files in express js

I have 4 files:

1) db.js - mongodb connection
2) socket.js - for all socket events
3) route.js - route for /
4) app.js - main start point for express app

I want to share same db instance from db.js in socket.js and route.js so that the connection to db is made only once.

I have tried 2 ways for this:

1) require db.js in both files, but this creates new connection every time require is called.
2) pass the collections in request object in db.js, but then how would I access the request object in socket.js in 

io.on("connection",function(socket){
 // request ??
})

How can it be solved?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You could move to a dependency injection setup rather than explicitly requiring db.js in each file, that would allow you to reuse your existing db connection:

main.js

// require and setup db like normal
var db = require('./db.js');
// require route, but now call it as a function and pass your db instance
var route = require('./route.js)(db);

route.js

module.exports = function(db, maybeOtherSharedResources) {
  // existing code from route.js
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!