简体   繁体   English

在具有许多路由器的Express应用中使用MongoClient.connect的最佳实践是什么?

[英]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.

相关问题 MongoClient.connect 失败,但不会抛出错误 - MongoClient.connect fails, but does not throw an error MongoClient.connect 在 node.js 中不工作 - MongoClient.connect not working in node.js 执行回调后如何终止MongoClient.connect? - How to terminate MongoClient.connect after executing its callback? NodeJS中的MongoClient.connect阻塞:async.map() - MongoClient.connect blocking in NodeJS: async.map() MongoClient.connect在网站的onload功能中不起作用 - MongoClient.connect doesn't work in a website's onload function 在其他模块中未读取从 MongoClient.connect() 导出 - Export from MongoClient.connect() is not being read in other module 在 Javascript Express 应用程序中存储机密的最佳实践 - Best practice store secrets in Javascript Express App 构造MongoClient和表达的最佳方法是什么:路由内的客户端还是客户端内的路由? - What's the best way to structure MongoClient and express: Client inside routes or routes inside client? 使用Express从您的提交中.gitignore API密钥的最佳实践是什么? - What is the best practice to .gitignore API keys from your commits using Express? node.js和express-使用多个中间件与回调-最佳实践是什么? - node.js and express - using multiple middlewares vs. callbacks - what's the best practice?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM