这是来自 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会在这种情况下打开第二个连接?
答案 0 :(得分:7)
Mongoose使用下面的本机mongo驱动程序,然后它使用连接池 - 我相信默认是5个连接(检查here)。
因此,当同时请求时,您的mongoose连接最多会同时使用5个连接。
由于user.save
和User.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
如果你在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}});
这将是它的主旨。