如何将变量传递给routes.index

发布于 2024-12-25 06:16:05 字数 294 浏览 3 评论 0原文

在文件 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巴黎盛开的樱花 2025-01-01 06:16:05

我设置了一个示例,说明如何通过将 db 作为参数传递给路由模块来实现此目的,并且该模块返回一个函数(其中 db 可见):

routes.index

module.exports = function (db) {
  return function(req, res, next) {
    // you can access db here
  }
}

<强>app.js

...
routes = {};
routes.index = require('./routes')(db);
...

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

module.exports = function (db) {
  return function(req, res, next) {
    // you can access db here
  }
}

app.js

...
routes = {};
routes.index = require('./routes')(db);
...
二智少女 2025-01-01 06:16:05

我认为在连接到数据库的库中,如果您尝试创建另一个连接(即:数据库接口是单例),则共享连接是相当标准的。您可以尝试简单地调用

db = mongoose.connect('mongodb://localeyes/expressdb');

paths/index.js 文件,它可能会使用相同的连接。我建议阅读代码,看看它是否会使用现有连接,或者是否在您每次调用它时都尝试重新连接。

编辑:再想一想,你还有另一个不那么美味的选择:
你可以像这样将其设置为全局

global.db = db;

,然后在你的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

db = mongoose.connect('mongodb://localeyes/expressdb');

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

global.db = db;

and then in your routes/index.js

var db = global.db;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文