node.js - 如何将变量传递给routes.index

标签 node.js mongodb express mongoose data-transfer

在文件app.js中我有:

  , mongoose = require('mongoose')
  , db = mongoose.connect('mongodb://localhost/expressdb');

  app.get('/', routes.index);

我有文件routes/index.js,如果我想将db变量传输到routes.index我该怎么办?

最佳答案

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

routes.index

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

app.js

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

关于node.js - 如何将变量传递给routes.index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8748451/

相关文章:

node.js - 防止开发人员推送带有 lint 错误的代码

node.js - 进口 Assets 发行, Electron 伪造

Java Spring Mongo 排序忽略大小写问题

node.js - Node Mongoose 更新两个集合

javascript - 具体网址路径

javascript - 为什么不将数据库查询的结果推送到变量中?

javascript - 在 Node.js 中使用 Import 命令

mongodb - 在Elasticsearch中尝试将MongoDB文档作为单独的类型导入

node.js - 在Express中使用多个MongoDB查询进行异步/等待

node.js - 在 Express : userid not found 中使用 rest api