猫鼬使用本地蒙戈驱动下,它反过来使用连接池 - 我相信,默认值是5个连接(检查here)。
所以,你的猫鼬连接将使用多达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
- 嘿,蒙戈本地驱动程序(这是用C++) - 这里有两个任务为你!
- 然后蒙戈驾驶员触发第一请求。它认为它可以打开更多的连接,然后打开更多的连接,所以它可以打开,也可以触发第二个请求,而无需等待第一个连接完成。
如果你调用的回调中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);
});
顺便说一句,你可以告诉猫鼬只使用一个连接,如果你需要,出于某种原因:
let connection = mongoose.createConnection(dbUrl, {server: {poolSize: 1}});
这将是它的要点。
了解更多关于MongoLab blog和Mongoose website。
感谢惊人的解释! –
我想补充一点,客户有一个更大的连接池,并不罕见,数百甚至数千。 –
@ MarkusWMahlberg可能,但我认为带有数百个连接的_client_不会那么频繁。我想,取决于用例。 – Zlatko