Monday 5 June 2017

mongoose: how to handle errors in find().cursor().on('data')?

I need to process my entire collection to update one field ('isActive') for every document based on an algorithm depending on some collection field.

I have written this method:

function updateCollectionActiveStatus(callback) {
  Person.find({}).cursor()
    .on('data', function(doc) { // handle data
      doc.isActive = check(doc); // external logic, irrelevant here
      doc.save(function(err) {
        if (err) {
          callback(err);
          // HOW TO STOP EXECUTION HERE, AND AVOID PROCESSING MORE DATA?
        })
    })
    .on('error', function(err) { // handle error
      callback(err);
    })
    .on('end', function() { // final callback
      callback();
    })
  ;
}

I ask: how to bail out of cursor data processing, should I get an error?
Of course a return after callback(err) should be ineffective...



via MarcoS

No comments:

Post a Comment