Mongoose.js 通过一次 connect() 调用创建到 MongoDB 的多个连接 [英] Mongoose.js creates multiple connections to MongoDB from one connect() call
问题描述
我正在 Node.js Express 应用程序中通过 Mongoose 与 MongoDB 建立单一连接:
I am making a single connection to MongoDB via Mongoose in Node.js Express app:
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('localhost', 'test');
然后我定义架构,然后是模型,最后是从数据库中提取所有用户的控制器:
I then define schema, followed by models, and lastly the controller that pulls all users from the database:
app.get('/users', function (req, res) {
return User.find(function (err, users) {
if (!err) {
return res.send(users);
}
});
});
这些数据库连接在应用程序启动期间打开,并且在 node.js 应用程序期间保持打开状态.
These DB connections open during the application start and they stay open for the duration of the node.js application.
困扰我的是为什么我打开了 5 个连接?一旦我关闭 node.js 应用程序,所有 5 个连接都将关闭.
What bothers me is why do I have 5 connections open? As soon as I close the node.js app, all 5 connections are closed.
相关说明:对于 REST API 服务器,最好始终打开 MongoDB 连接.还是根据每个用户请求手动打开/关闭连接更好?
Related note: For a REST API server is it better to have MongoDB connection always open. Or is it better to manually open/close connections per each user request? d
推荐答案
那是因为 Mongoose 使用了 5 个连接池(默认情况下),这些连接在整个应用程序中共享.为了获得最佳性能,最好让它们保持打开状态.
That's because Mongoose uses a pool of 5 connections (by default) that are shared throughout your application. For best performance, it's best to just leave them open.
您可以通过将选项参数更改为 mongoose.connect
来更改默认行为.例如:
You can alter the default behavior via the options parameter to mongoose.connect
. For example:
mongoose.connect('localhost', 'test', { server: { poolSize: 3 }}); // Use 3 connections
这篇关于Mongoose.js 通过一次 connect() 调用创建到 MongoDB 的多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!