Why does the mongoose open two connections?

This is a simple file from mongoose quick guide.

mongoose.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Chat');

var userSchema = mongoose.Schema({
  name: String
});

var User = mongoose.model('User', userSchema);
var user = new User({name: 'Andy'});

user.save(); // 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 the method db.once, but the effect is the same.

Why does mongoose open a second connection in this case?

mongodb

+4
source share
1 answer

Mongoose uses its own mongo driver under it, and it, in turn, uses the connection pool - I believe that the default is 5 connections (check here ).

This way your mongoose connection will use up to 5 concurrent connections if it has concurrent requests.

user.save User.find , . "" node:

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

node , ( return). :

  • save
  • find
  • , mongo ( ++) - !
  • mongo . , , , , , .

find save, , , , .

:

// open the first connection
user.save(function(err) {

  if (err) {

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

promises:

user.save().exec().then(function(){
  return User.find(query);
})
.then(function(users) {
  console.log(users);
})
.catch(function(err) {
  // if either fails, the error ends up here.
  console.log(err);
});

, , , - :

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

.

MongoLab - Mongoose.

+5

Source: https://habr.com/ru/post/1629622/


All Articles