大佬教程收集整理的这篇文章主要介绍了node.js – 为什么mongoose会打开两个连接?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_435_5@mongoose.js
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/Chat'); var userscheR_493_11845@a = mongoose.scheR_493_11845@a({ name: String }); var User = mongoose.model('User',userscheR_493_11845@a); 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
为什么mongoose会在这种情况下打开第二个连接?
因此,当有同时请求时,您的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.
然后节点运行时读取这些,运行整个函数(直到返回).然后它看着它的笔记:
>我本来应该称之为拯救
>我也需要打电话给这个发现
>嘿,mongo本机驱动程序(用C编写) – 这里有两个任务给你!
>然后mongo驱动程序触发第一个请求.并且它看到它允许打开更多连接然后一个,所以它确实,并且也发出第二个请求,而不是等待第一个完成.
如果你在回调中调用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(/*...*/); });
或类似承诺:
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}});
这将是它的要点.
以上是大佬教程为你收集整理的node.js – 为什么mongoose会打开两个连接?全部内容,希望文章能够帮你解决node.js – 为什么mongoose会打开两个连接?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。