如何将变量传递给routes.index
在文件 app.js
中,我有:
, mongoose = require('mongoose')
, db = mongoose.connect('mongodb://localhost/expressdb');
app.get('/', routes.index);
并且我有文件 routes/index.js
,如果我想将 db
变量传输到 routes.index
我该怎么办?
In file app.js
i have:
, mongoose = require('mongoose')
, db = mongoose.connect('mongodb://localhost/expressdb');
app.get('/', routes.index);
and i have file routes/index.js
, If I want to transfer db
variable to routes.index
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我设置了一个示例,说明如何通过将 db 作为参数传递给路由模块来实现此目的,并且该模块返回一个函数(其中 db 可见):
routes.index
<强>app.js
I've setup an example on how you can achieve that, by passing the db as a parameter to the route module, and that module returns a function (in which db is visible):
routes.index
app.js
我认为在连接到数据库的库中,如果您尝试创建另一个连接(即:数据库接口是单例),则共享连接是相当标准的。您可以尝试简单地调用
paths/index.js 文件,它可能会使用相同的连接。我建议阅读代码,看看它是否会使用现有连接,或者是否在您每次调用它时都尝试重新连接。
编辑:再想一想,你还有另一个不那么美味的选择:
你可以像这样将其设置为全局
,然后在你的routes/index.js中
var db = global.db;
I think it's fairly standard in libraries that connect to a database for the connection to be shared if you try to create another connection (ie: the DB interface is a singleton). You could try simply calling
in your routes/index.js file, and it will likely use the same connection. I'd recommend reading the code to see if it will use an existing connection or if it tries to reconnect every time you call it.
edit: on second thought, you have another, less savory option:
You could make it global like so
and then in your routes/index.js
var db = global.db;