如何使用 Express 路由器与我的 mongo 实例保持持久连接
How to keep a persistent connection to my mongo instance with express router
我有一个快速路由器,例如:
var express = require('express')
, router = express.Router()
, bodyParser = require('body-parser')
, mongoclient = require('mongodb').MongoClient
, dbconfig = require('../assets/config.db.json');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
var term = req.body.searchTerm;
mongoclient.connect(dbconfig.url, (err, db) => {
db.accessDatabase(term, (err, result) => {
db.close();
if (err) res.json({result: err});
res.json(result);
});
});
});
module.exports = router;
我已经读到,如果每次 REST 调用都需要大量开销来连接我的数据库,那么我需要为使用此 REST 的人建立持久连接 API。在我的路由器中执行此操作的正确方法是什么?现在每次收到 post 请求时,它都会打开一个连接,访问数据库,然后关闭连接。
编辑:为了清楚起见,我使用了 db.accessDatabase(),但这并不是我的代码中使用的实际语法。
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.
就我个人而言,我是这样做的
var params = {/*config, etc... required to bootstrap models */}
require('./app/models')(params)
.then(afterModels)
.then(startServer)
function afterModels(theModels) {
params.models = theModels
let providers = require('./app/providers')(params)
params.providers = providers
// boot strap routes
require('./app/routes')(params)
// controllers can use params which has models (db object,e tc.. inside)
}
function startServer() {}
我有一个快速路由器,例如:
var express = require('express')
, router = express.Router()
, bodyParser = require('body-parser')
, mongoclient = require('mongodb').MongoClient
, dbconfig = require('../assets/config.db.json');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
var term = req.body.searchTerm;
mongoclient.connect(dbconfig.url, (err, db) => {
db.accessDatabase(term, (err, result) => {
db.close();
if (err) res.json({result: err});
res.json(result);
});
});
});
module.exports = router;
我已经读到,如果每次 REST 调用都需要大量开销来连接我的数据库,那么我需要为使用此 REST 的人建立持久连接 API。在我的路由器中执行此操作的正确方法是什么?现在每次收到 post 请求时,它都会打开一个连接,访问数据库,然后关闭连接。
编辑:为了清楚起见,我使用了 db.accessDatabase(),但这并不是我的代码中使用的实际语法。
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.
就我个人而言,我是这样做的
var params = {/*config, etc... required to bootstrap models */}
require('./app/models')(params)
.then(afterModels)
.then(startServer)
function afterModels(theModels) {
params.models = theModels
let providers = require('./app/providers')(params)
params.providers = providers
// boot strap routes
require('./app/routes')(params)
// controllers can use params which has models (db object,e tc.. inside)
}
function startServer() {}