gpt4 book ai didi

node.js - 为什么 Mongoose 打开两个连接?

转载 作者:可可西里 更新时间:2023-11-01 09:10:39 26 4
gpt4 key购买 nike

这是 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 在底层使用 native mongo 驱动程序,它又使用连接池 - 我相信默认值为 5 个连接(检查 here)。

因此,当您的 mongoose 连接有并发请求时,它最多会同时使用 5 个连接。

因为 user.saveUser.find 都是异步的,所以它们会同时完成。那么你的“程序”告诉 Node :

1. Ok, you need to shoot a `save` request for this user.
2. Also, you need to fire this `find` request.

Node 运行时然后读取这些,运行整个函数(直到 return)。然后它查看它的注释:

  • 我应该调用这个save
  • 我还需要调用这个find
  • 嘿,mongo native 驱动程序(用 C++ 编写)- 这里有两个任务给你!
  • 然后 mongo 驱动程序触发第一个请求。它发现它可以打开比一个连接更多的连接,所以它也打开了第二个请求,而无需等待第一个请求完成。

如果您在 save 的回调中调用 find,它将是连续的,并且驱动程序可能会重用它已经拥有的连接。

例子:

// 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(/*...*/);
});

或类似的 promise :

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 blog 的信息和 Mongoose website .

关于node.js - 为什么 Mongoose 打开两个连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com