为什么mongoose打开两个连接?

时间:2016-02-19 21:18:20

标签: node.js mongodb mongoose

这是来自 mongoose快速指南

的简单文件

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

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

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

mongodb

1 个答案:

答案 0 :(得分:7)

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

因此,当同时请求时,您的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.

然后节点运行时读取这些内容,运行整个函数(直到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(/*...*/);
});

或类似承诺:

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

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

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

这将是它的主旨。

详情阅读MongoLab blogMongoose website