为什么mongoose打开两个连接?

The*_*son 4 mongoose mongodb node.js

这是一个来自猫鼬快速指南的简单文件

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
Run Code Online (Sandbox Code Playgroud)

我尝试使用db.once方法,但效果相同.

为什么mongoose会在这种情况下打开第二个连接?

MongoDB的

Zla*_*tko 7

Mongoose使用下面的本机mongo驱动程序,然后它使用连接池 - 我相信默认是5个连接(在这里检查).

因此,当有同时请求时,您的mongoose连接将最多使用5个同时连接.

而且,由于这两个user.saveUser.find是异步的,那些将同时进行.那么你的"程序"告诉节点:

1. Ok, you need to shoot a `save` request for this user.
2. Also, you need to fire this `find` request.
Run Code Online (Sandbox Code Playgroud)

然后节点运行时读取这些,遍历整个函数(直到a return).然后它看着它的笔记:

  • 本来应该叫这个 save
  • 我也需要打个电话 find
  • 嘿,mongo本机驱动程序(用C++编写) - 这里有两个任务给你!
  • 然后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(/*...*/);
});
Run Code Online (Sandbox Code Playgroud)

或类似承诺:

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);
});
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果需要,你可以告诉mongoose只使用一个连接,原因如下:

let connection = mongoose.createConnection(dbUrl, {server: {poolSize: 1}});
Run Code Online (Sandbox Code Playgroud)

这将是它的要点.

阅读更多关于MongoLab博客Mongoose网站的信息.