Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

107
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?

8 months 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
}
8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.