1

I am new to Node and MongoDB, so please forgive me if I sound too naive.

I have a DB class that creates a connection to 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();
}

Next I have another module that creates a Schema for MongoDB

schema.js

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

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

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

Then I have another module that makes use of this Schema to save objects

logger.js

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

exports.log = () => {

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

The Main module

Main.js

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

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

When I run node Main.js, everything is saved, but when I check the MongoDB with the command db.serverStatus.connections, I see 6 connections open.

I don't know how it's getting there. I know the command mongo itself keep a connection open, but where are the other 5 connections coming from?

I have checked this, which seems to suggest that Mongoose opens 5 connections for an application, but my application is firing just one transaction, where is the need to open 5 connection then? Couldn't it be done with just one?

1 Answer 1

2

Mongoose is managing the connections itself; it tries to optimize the speed of the request.

You are seeing it like you are using only one transaction, but behind the scene mongoose is probably doing much more than you expect.


You can modify the number of connection mongoose can open using the parameter poolSize.


Example :

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

Try it with poolSize equals to 1 and see how much time it takes to execute your transaction, you'll have your answer.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! That indeed answered my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.