繁体   English   中英

使用NodeJS和Mongoose在MongoDB中打开了多个连接

[英]More than one connection opened in MongoDB using NodeJS and Mongoose

我是Node和MongoDB的新手,所以如果我听起来太天真,请原谅我。

我有一个数据库类,用于创建与MongoDB的连接

db.service.js

const mongoose = require("mongoose");
const fs = require("fs");
const dbConfigs = JSON.parse(fs.readFileSync("/configs.json"));
const dbHost = dbConfigs.DB_HOST;
const dbName = dbConfigs.DB_NAME;
const dbPort = dbConfigs.DB_PORT;
const dbUrl = "mongodb://" + dbHost + ":" + dbPort + "/" + dbName;
const dbOptions = {
    useNewUrlParser: true
};

let dbConnection = mongoose.createConnection(dbUrl, dbOptions);
exports.getConnection = () => {
    if (dbConnection)
        return dbConnection;
}

exports.closeConnection = () => {
    if (dbConnection)
        return dbConnection.close();
}

接下来,我还有另一个模块,该模块为MongoDB创建架构

schema.js

const connection = require("./db.service").getConnection();
const Schema = require("mongoose").Schema;

const SampleSchema = new Schema({...})

exports.Sample = connection.model("Sample", SampleSchema);

然后我有另一个模块,利用该模式保存对象

logger.js

const Sample = require("./schema").Sample;

exports.log = () => {

let body = {....};
let sampleObj = new Sample(body);
return sampleObj.save(sampleObj);

主模块

Main.js

const logger = require("./logger");

for (let i=0; i < 100; i++) {
    logger.log();
}

当我运行node Main.js ,所有内容都会保存,但是当我使用db.serverStatus.connections命令检查MongoDB时,我看到有6个连接打开。

我不知道怎么到那里。 我知道mongo命令本身会使连接保持打开状态,但其他5个连接来自何处?

我已经检查过 ,这似乎表明Mongoose为一个应用程序打开了5个连接,但是我的应用程序仅触发了一个事务,那么哪里需要打开5个连接? 不能只用一个完成吗?

猫鼬在管理连接本身。 它尝试优化请求的速度。

您会看到它就像在使用一次事务,但是在幕后猫鼬的作用可能超出您的预期。


您可以使用参数poolSize修改可以打开的猫鼬连接数。


范例

const dbOptions = {
    useNewUrlParser: true,
    poolSize: 1,
};

poolSize等于1的情况下尝试一下,看看执行事务需要花费多少时间,您将得到答案。

暂无
暂无

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

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