Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js creates multiple connections to MongoDB from one connect() call

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);
    }
  });
});

These DB connections open during the application start and they stay open for the duration of the node.js application.

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. enter image description here

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

like image 696
Sahat Yalkabov Avatar asked Sep 29 '12 20:09

Sahat Yalkabov


People also ask

Does MongoDB allow multiple connections?

MongoDB allows multiple clients to read and write the same data. To ensure consistency, MongoDB uses locking and concurrency control to prevent clients from modifying the same data simultaneously.

How does Mongoose Connect work?

Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.

Is Mongoose connect asynchronous?

The connect() method provided by the Mongoose supports both JavaScript promises and async-await syntax.

Does Mongoose connect create a database?

Bookmark this question. Show activity on this post. databases are created on first write operation.


1 Answers

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.

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
like image 65
JohnnyHK Avatar answered Oct 17 '22 03:10

JohnnyHK