如何在Nodejs和Express中重用Db连接

问题描述 投票:2回答:2

我想知道在我的情况下重用数据库连接的最佳方法是什么,它是NodeJs中的couchbase连接以及express。对于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();
}

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

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

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

node.js express couchbase
2个回答
3
投票

您是否尝试过将init代码从中间件函数中删除? Couchbase Documentation没有表明它被这样使用。虽然这个例子是在vanilla Node中。通过将其置于中间件功能中,每次服务器收到请求时,您都将重新连接到数据库。

我连接到顶级app.js主体中的Mongo服务器,这允许连接保持不变。然后我可以在模型和控制器中导入我需要的猫鼬参考,以概述如何获取某些数据,然后在相关路径端点内调用控制器的方法。

编辑以显示将存储桶指定为控制器类字段的示例

在你的app.js中

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

// ...app.js

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

// app.js...

在你的控制器中

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

});

1
投票

您可以创建一个专门的模块(例如db.js),您可以在其中为您的连接池实现单例。

// pseudo-code
export const getDb = () => {
  let db

  if (!db) {
    const connection = createConnectionPool()
    db = connection.db
  }

  return db
}

可以在中间件和代码的其他部分导入此函数。

© www.soinside.com 2019 - 2024. All rights reserved.