【问题标题】:More than one connection opened in MongoDB using NodeJS and Mongoose使用 NodeJS 和 Mongoose 在 MongoDB 中打开了多个连接
【发布时间】:2018-08-28 11:43:25
【问题描述】:

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

我有一个创建与 MongoDB 的连接的 DB 类

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 的模块

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 个连接来自哪里?

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    Mongoose 自己管理连接;它试图优化请求的速度。

    你看到它就像你只使用一个事务,但在幕后 mongoose 可能做的比你预期的要多得多。


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


    示例

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

    试试poolSize等于1,看看执行你的交易需要多少时间,你就会得到答案。

    【讨论】:

    • 谢谢!!这确实回答了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 2019-03-14
    • 1970-01-01
    • 2017-03-25
    • 2013-01-18
    • 2021-03-17
    • 2013-01-10
    • 2017-12-18
    相关资源
    最近更新 更多