1

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?

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works well for socket.js file but not for route.js. The previously defined API in route.js becomes 404. route.js now - var express = require('express'); var router = express.Router(); module.exports = function(model){ router.post('/save', function(req, res) { var myCollection = model().myCollection; if (myCollection) { //save } else { //error } });
You need to ensure that you are returning your routes/etc. from files you end up exporting as functions.
Implemented and it is working, now the poblem is when I refresh on client side it gives error in route.js on line var myCollection = model().myCollection , says - Trying to open unclosed connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.