如何在Express 4.0路由器中间件中重用MongoClient对象?

在Express 3.x中,我能够为整个应用程序重用一个MongoClient对象。

app.js

var routes = require('./routes'); // Routes for our application MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) { "use strict"; if(err) throw err; app.engine('html', cons.swig); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); app.use(express.cookieParser()); app.use(express.bodyParser()); // Application routes routes(app, db); app.listen(8082); console.log('Express server listening on port 8082'); }); 

路线/ index.js

 module.exports = exports = function(app, db) { //do something } 

在Express 4.0中,他们引入了路由器中间件,就像这样

 var routes = require('./routes/index'); app.use('/', routes); 

我怎样才能将MOngoClient对象传递给路由器中间件?

您可以使用单独的模块(如'Mongo.js'定义连接并存储您的MongoClient instance(_db)

然后在指定的启动脚本中包含该模块(eg bin/www by default)并创build一个连接。 这样连接将只打开一次,但是你也可以在你的路由中重用数据库object (_db) ,只需要包含'Mongo.js'

您仍然可以通过修改routes/index.js来使用相同的模式

 var express = require('express'); var router = express.Router(); module.exports = function(db) { /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); return router; } 

注意最后的return router

在你的app.js

 MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) { ... app.use('/', routes(db)) ... } 

基本上通过创build一个处理所有数据库操作的类,它可以减less应用程序代码中的混乱。 另外,callback的使用可以让你有效地使用通常在mongodb操作中得到的输出。

下面的示例代码将清除名为“records”的样本集合中的所有logging,从而有效地向callback(如果有)抛出错误,并将结果抛出callback以供您使用。

只要你喜欢使用MongoDB网站上的通常的CRUD方法

@ http://mongodb.github.io/node-mongodb-native/2.2/tutorials/crud/

检查下面的代码。

 class SimpleMongoManager { constructor(dbURL) { if (!dbURL) { console.error(`dbURL required!`); throw (`@ constructor`); } this.mongoClient = require('mongodb').MongoClient; this.assert = require('assert'); this.dbURL = dbURL; this.collectionName = collectionName; } initialize(callback) { var self = this; this.mongoClient.connect(this.dbURL, function(err, db) { if (err) { console.error(err); throw (`@ initialize @ connect`); } else { self.db = db; if (callback) { callback(db); } } }); } gracefulExit() { var self = this; if (self.db) { self.db.close(); } } debugClearRecords(callback){ var self = this; self.db.collection("records").deleteMany({}, function(err, result) { if(err){ console.error(err); throw("@ debugClearRecords @ deleteMany"); }else{ if(callback){ callback(null, result.deletedCount); } } }); } } /* Sample Usage */ var smInstance = new SimpleMongoManager("mongodb://localhost:27017/anterior"); smInstance.initialize(function(db){ console.log("DB Connection OK!"); }); smInstance.debugClearRecords(function(err, result){ console.log(err); console.log(result); }); /* Sample Route */ app.get('/clear_records', function(req, res){ /* Any checks here, if user is admin, whatever. */ smInstance.debugClearRecords(function(err, result){ console.log(err); console.log(result); res.redirect('/'); }); });