node.js - 如何在 Nodejs 和 Express 中重用数据库连接

标签 node.js express couchbase

我想知道在我的案例中重用数据库连接的最佳方法是什么,它在 NodeJs 和 express 中重用 couchebase 连接。 对于 Express 部分,我创建了一个这样的中间件

var couchbase = require('couchbase')
var config = require('../config/config')

module.exports = (req,res,next)=>{
  var cluster = new couchbase.Cluster(config.cluster)
  cluster.authenticate(config.userid, config.password)
  let bucket = cluster.openBucket(config.bucket);
  bucket.manager().createPrimaryIndex(function() {});
  req.bucket = bucket;
  req.N1qlQuery = couchbase.N1qlQuery;
  next();
}

这在 express 应用程序中运行良好,因为我告诉它

const dbSessionMiddleware = require('../middleware/couch')
app.use(dbSessionMiddleware) 

这允许我通过 req.bucket 访问它。我的问题是我的应用程序中有 Controller ,以防万一可能会调用辅助函数,它们可能会调用另一个函数来取回一些数据。我想避免必须继续将请求对象向下传递 5 个级别左右才能使用中间件。有没有更好的方法可以将连接/存储桶暴露给正常功能?

最佳答案

您是否尝试过将初始化代码从中间件函数中取出? Couchbase Documentation没有显示它被那样使用。尽管这个例子是在 vanilla Node.js 中。通过将其置于中间件函数中,您将在每次服务器收到请求时重新连接到数据库。

我在顶级 app.js 主体中连接到我的 Mongo 服务器,这允许连接持续存在。然后我可以在我的模型和 Controller 中导入我需要的 Mongoose 引用来概述如何获取某些数据,然后在相关路由端点内调用 Controller 的方法。

经过编辑以显示将存储桶分配为 Controller 类字段的示例

在你的 app.js 中

const couchbase = require("couchbase");
const config = require("../config/config");

// ...app.js

const CouchController = require("../controllers/CouchController")(couchbase, config);

// app.js...

在你的 Controller 中

class CouchController {

  constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

  doSomeQuery(queryString, callback) {

    // Use your query however its meant to be used. I'm not familiar with couchbase queries.
    this.bucket.manager().createPrimaryIndex(function() {

      this.bucket.query(
        this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
        [queryString],
        callback(err, result)
      )

    });
  }

}

然后从路由内部调用您的 Controller 方法

router.get("/", function(req, res, next) {

  let searchParam = req.query.someParam;

  CouchController.doSomeQuery(searchParam)
    .then(result => {
      res.json(result);
    });

});

关于node.js - 如何在 Nodejs 和 Express 中重用数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54856623/

相关文章:

python - 在 Centos7 上从源代码安装 couchbase-python-client

node.js - Sequelize .save() 在实例上不起作用

node.js - pm2 创建了一个 "source"目录并将我的所有文件复制到其中,为什么?

javascript - 将对象保存在模块中并从不同的模块访问它

javascript - 等待查询结果

java - telnet 和 Java (com.danga) 之间的 Memcached 跨客户端兼容性问题

node.js - cluster.fork() 是否保证使用不同的 CPU 内核?

javascript - WebSocket 连接超时

node.js - 为什么我的异步等待无法正常工作

javascript - Node.js 无法将字符串传递到 res.send() 中;不明确的