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