简体   繁体   English

mongodb和expressjs的最佳做法

[英]Best practices with mongodb and expressjs

I want to know how to handle mongo connections with express. 我想知道如何使用express处理mongo连接。

My questions are: 我的问题是:

Is it a good idea create a middleware to handle every request and before execute it, connect to mongo? 创建一个中间件来处理每个请求并在执行之前连接到mongo是一个好主意吗?

Is it a good idea create a middleware to handle every request and after make response, close mongo connection? 创建一个中间件来处理每个请求,并在做出响应后关闭mongo连接,这是一个好主意吗?

Best practice is to call mongoose.connect during your application's startup and just leave it open. 最佳实践是在应用程序启动期间调用mongoose.connect并将其保持打开状态。 That call creates a connection pool that is shared across all Mongoose models, by default. 默认情况下,该调用会创建一个在所有Mongoose模型之间共享的连接池。

The default pool size is 5, but you can tweak that in your call's options : 默认池大小为5,但您可以在通话选项中进行调整:

const options = {
    poolSize: 10
};
mongoose.connect('mongodb://localhost/test', options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM