0

I'm trying to update the states with the highest weather, adding a field, but when i try to do the loop, the connection gets closed! It only do the first update, but the next it says

MongoError: Connection Closed By Application

Why? I'm not closing the connection.

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
    var state = "";
    var query = {};
    if(err) throw err;

    var grades = db.collection('data');

    var options = { 'sort' : [['State', 1], ['Temperature', -1]] };
    var cursor = grades.find({}, {}, options);

    cursor.each(function(err, doc) {
        if(err) throw err;
        if(doc == null) {
            return db.close();
        }

        if(state != doc.State){
            state = doc.State;
            console.dir(state);


            query['_id'] = doc['_id'];

            grades.update(query, {$set: {"month_high": true}}, function(err, updated){
                if(err) throw err;

                console.dir("Se han modificado " + updated + " Elementos!");
                // return db.close(); I comment this line and this stills closing!!!!
            });
        }

    });
});
Stennie
  • 63,885
  • 14
  • 149
  • 175
Cris_Towi
  • 615
  • 1
  • 13
  • 25
  • 3
    There's another `return db.close()` in your code that may be closing the connection before other successful operations can complete. Also, if any of these functions are providing `err`s, `throw`ing them may not make them seen. The internals of `mongodb` can `catch` and handle them for you since it's calling the callbacks. Try logging them instead, `return console.error('Error:', err);`. – Jonathan Lonowski Jun 17 '14 at 15:28

1 Answers1

0

See this post for the solution Removing documents from a mongodb

As someone wrote: "You should not use throw for callback, throw is good for function stack"

Community
  • 1
  • 1
carloscarcamo
  • 331
  • 1
  • 7
  • 12