Mongoose Attempt to open a closed connection (callback hell)

I want to add a loop to database records. But the mongoose wrote that I did not close the open connection. Mongoose Attempts to open a closed connection. How to make it all sync? His reverse 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()
        });
+4
source share
3 answers

In fact, you do not need to open / close your connection for each request (for details, see here ).

Instead, you can simply open your connection immediately after starting your application, and then just close it when the application closes.

, , / .

+4

-, , . , :

createConnection() connect().

:

db = mongoose.createConnection('mongodb://localhost/mydb');
+2

, , , mongoose.connect , .

: mongoose.connect .

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

, .

0

Source: https://habr.com/ru/post/1532359/


All Articles