如何建立可以从其他文件访问的全局mongodb连接

时间:2018-12-23 20:20:16

标签: node.js mongodb express

所以我有这个主服务器文件index.js:

const express = require('express')
const app = express()

const route = require('./route')

app.use('/main', route)
app.listen(3000)

然后有route.js文件:

const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {
  res.send('Hello from main')
})

module.exports = router

顾名思义,我该如何建立全局mongodb连接,这样就不必在每个路由上都建立与数据库的新连接?
谢谢!

1 个答案:

答案 0 :(得分:3)

我很惊讶对此没有答案。最常见的模式是在单独的模块中初始化数据库连接,并将其导入需要的任何文件中。

以下内容摘自这篇较长的文章https://itnext.io/how-to-share-a-single-database-connection-in-a-node-js-express-js-app-fcad4cbcb1e,并以回调样式编写。我已经对其进行了一些更新,如下所示:

idealButton.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    idealButton.leftAnchor.constraint(equalTo: navigationBar.leftAnchor, constant: 20),
    idealButton.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -6),
    idealButton.heightAnchor.constraint(equalToConstant: 32),
    idealButton.widthAnchor.constraint(equalToConstant: 32)
])

这是一个没有分号的基于诺言的版本,这就是我自己可以做的。这些功能都将成为在项目之间重用的候选者。

/* Callback Style */

const assert = require("assert");
const client = require("mongodb").MongoClient;
const config = require("../config");
let _db;
module.exports = {
    getDb,
    initDb
};

function initDb(callback) {
  if (_db) {
    console.warn("Trying to init DB again!");
    return callback(null, _db);
  }
  client.connect(config.db.connectionString, 
  config.db.connectionOptions, connected);
  function connected(err, db) {
    if (err) {
      return callback(err);
    }
    console.log("DB initialized - connected to: " + 
      config.db.connectionString.split("@")[1]);
    _db = db;
    return callback(null, _db);
  }
}

function getDb() {
  assert.ok(_db, "Db has not been initialized. Please called init first.");
  return _db;
}

 /******************************************************************/
//The client
const initDb = require("./db").initDb;
const getDb = require("./db").getDb;
const app = require("express")();
const port = 3001;
app.use("/", exampleRoute);
initDb(function (err) {
    app.listen(port, function (err) {
        if (err) {
            throw err; //
        }
        console.log("API Up and running on port " + port);
    });
);
function exampleRoute(req, res){
 const db = getDb();
 //Do things with your database connection
 res.json(results);
}