当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Mongoose Trying to open unclosed connection (callback hell)

问题描述:

I want to add a loop to the database records. But mongoose wrote that I did not close the open connection. Mongoose Trying to open unclosed connection. How to make the whole thing went in sync? Its callback hell in my code

 app.get("/dobavit/", function(req, res) {

for(var i=50; i>0; i--)

{

InsertAXIXA("analitika",i,function(data){

});

}

res.end();

});

function InsertAXIXA(qwerty,page,callback){

mongoose.connect('mongodb://localhost/gazprom')

var parsedResults = [];

var req = request('http://xxx.ru/'+qwerty+"?page="+page, function (error, response, html) {

if (!error && response.statusCode == 200) {

// str = iconv.decode(html, 'utf-8');

var $ = cheerio.load(html);

$('.col-1 .col-first').each(function(i, element){

var buf = $(this);

var zagolovok = buf.children(0).children().children().eq(0).text();

var previewText = buf.children(2).children().eq(0).text();

var url = buf.children(0).children().children().eq(0).attr('href');

var picUrl = buf.children(1).children().eq(0).children().children().eq(0).attr('src');

var metadata = {

zagolovok:zagolovok,

previewText:previewText,

url:url,

typeOfnews:qwerty,

picUrl:picUrl,

qwerty:qwerty

};

var news =new News({

zagolovok: zagolovok,

previewText: previewText,

url:url,

picUrl:picUrl,

qwerty:qwerty

// created_at:Date.today()

});

news.save(function(err, news,affected){

});

parsedResults.push(metadata);

});

callback(parsedResults);

}

mongoose.connection.close()

});

网友答案:

You shouldn't actually need to open/close your connection on every request (see here for more about that).

Instead, you can just open your connection once when your app starts and then just let it close when the app closes.

If you leave the connection open, you can reuse the connections instead of wasting time/resources establishing a new one every time that function is called.

网友答案:

In my opinion, you are trying to create another connection without closing the current one. So, you might want to use:

createConnection() instead of connect().

In your case, it would look like this:

db = mongoose.createConnection('mongodb://localhost/mydb');
网友答案:

i was getting the same error today, the solution which i found is, we should not call the mongoose.connect function in loop or anywhere in the code which is being executed again and again.

so my example is, i was doing mongoose.connect on all request of app.

app.all("*",function(){
    mongoose.connect();
})

Your code is somewhat similar to because in loop you are calling function and in function you are opening connection.

Thanks

分享给朋友:
您可能感兴趣的文章:
随机阅读: