貓鼬使用本地蒙戈驅動下,它反過來使用連接池 - 我相信,默認值是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