The Reason The Reason - 1 year ago 83
Node.js Question

Why mongoose opens two connections?

It's a simple file from mongoose quick guide


var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
name: String

var User = mongoose.model('User', userSchema);
var user = new User({name: 'Andy'});; // if i comment it mongoose will keep one connection

User.find({}, function(err, data) { console.log(data); }); // the same if i comment it

I tried to use
method, but effect the same.

Why does mongoose open the second connection in this case?


Answer Source

Mongoose uses native mongo driver underneath, and it in turn uses connection pooling - I believe the default is 5 connections (Check here).

So your mongoose connection will use up to 5 simultaneous connections when it has simultaneous requests.

And since both and User.find are asynchronous, those will be done simultaneously. So what your "program" tells node:

1. Ok, you need to shoot a `save` request for this user.
2. Also, you need to fire this `find` request.

The node runtime then reads these, runs through the whole of your function (until a return). Then it looks at it's notes:

  • I was supposed to call this save
  • I also need to call this find
  • Hey, mongo native driver (which is written in C++) - here are two tasks for you!
  • and then the mongo driver fires the first request. And it sees it is allowed to open more connections then one, so it does, and fires the second request too, without waiting for the first to finish.

If you called the find within a callback to save, it would be sequential, and the driver would probably reuse the connection it already had.


// open the first connection {

  if (err) {

    console.log('I always do this super boring error check:', err);
  // Now that the first request is done, we fire the second one, and
  // we probably end up reusing the connection.

Or similar with promises:{
  return User.find(query);
.then(function(users) {
.catch(function(err) {
  // if either fails, the error ends up here.

By the way, you can tell mongoose to use only one connection if you need to, for some reason:

let connection = mongoose.createConnection(dbUrl, {server: {poolSize: 1}});

That would be the gist of it.

Read more on MongoLab blog and Mongoose website.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download