为什么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的

Mongoose在下面使用本地mongo驱动程序,而它又使用连接池 – 我相信默认是5个连接(请点击这里 )。

所以你的mongoose连接最多可以同时使用5个连接。

而且由于user.saveUser.find都是asynchronous的,这些将同时完成。 那么你的“程序”告诉节点:

 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 ++编写) – 这里有两个任务给你!
  • 然后芒戈司机发出第一个要求。 而且它认为它可以打开更多的连接,然后就可以打开更多的连接,并且也可以触发第二个请求,而不必等到第一个连接完成。

如果您在callback中调用了findsave ,那么这将是顺序的,并且驱动程序可能会重新使用已有的连接。

例:

 // 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博客和Mongoose网站上阅读更多信息 。