在express js的不同文件中访问db连接的同一个实例

我有4个文件:

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 

我想从db.js in socket.js and route.js共享相同的数据库实例,以便连接到数据库只有一次。

我已经尝试了2种方法:

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

如何解决?

你可以移动到dependency injection设置,而不是在每个文件中显式地要求db.js ,这将允许你重用你现有的db连接:

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 }