[英]What is the best practice for using MongoClient.connect in an Express app with lots of routers?
I have an app that does this kind of thing multiple times: 我有一个可以多次执行此类操作的应用程序:
app.get('/', function(req, res){
MongoClient.connect(dbUrl, function(err, db){
//work with db data
});
});
But then I heard somewhere that it's better practice to connect to the database once, and use that connection on the whole thing. 但是后来我听到某个地方,最好是一次连接到数据库,然后在整个过程中使用该连接。 So does that mean something like this?:
那是否意味着这样的事情?:
MongoClient.connect(dbUrl, function(err, db){
app.get('/', function(req, res){
//do some stuff
});
app.get('/other', function(req, res){
//do some stuff
});
//
//more routers....
//
});
So which of these two methods would be considered better practice? 那么,这两种方法中的哪一种被认为是更好的做法? And what makes it better?
什么使它变得更好? What is the difference?
有什么区别? And is there a better way?
还有更好的方法吗?
Connect once, watch for connection errors: 连接一次,注意连接错误:
mongoose.connect(MONGO_URI);
var dbConnection = mongoose.connection;
dbConnection.on('error', console.error.bind(console, 'connection error...'));
dbConnection.once('open', function callback() { console.log('DB opened'); });
Use dbConnection
when you need to database access. 需要数据库访问时,请使用
dbConnection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.