1

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.insertionDate) { // 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...

NOTE: answering @Neil Lunn comment, I do not intend to 'rollback', but simply avoid processing more data after an error... Hope this is sufficiently 'specific'...

NOTE 2: If anybody knows a better/sleeker/cleverer/more atomic way to update one field (depending on other fields of that document) on every document of a collection using mongoose, please let me know, it should be accepted as correct answer...

MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • Well you really should not be using a `.find()` => "modify" => `.save()` pattern for starters. I would be looking to see if your *"extneral logic"* could actually be adapted to a more "atomic" update pattern. In general though It's not really clear what you are asking here. *"How do I rollback on error?"* Maybe? For the general question of "rollback", that has been answered before. As to how to handle? It's a bit broad. So generally speaking you need to be a lot more "specific". – Neil Lunn Jun 06 '17 at 01:57
  • @Neil Lunn: see question edit... – MarcoS Jun 06 '17 at 09:36
  • So what do you "think" happens when an error occurs here? Do you "think" more events are handled by "on"? Do you "think" the code executes in "end"? The reason you are defining these event handlers is ...? Still looking for the question. Which is?? – Neil Lunn Jun 06 '17 at 09:40
  • @Neil Lunn: I think `on('data')` functon is called for every document in collection. Am I wrong? I ask how to avoid processing *more* documents after a `doc.save()` should error me out... – MarcoS Jun 06 '17 at 13:51
  • `.on('error')` is an "error handler" thus it gets reached when the stream is "broken" . So no, when an error is reached no more `'data' events are emitted. See the [documentation](https://nodejs.org/api/stream.html) – Neil Lunn Jun 06 '17 at 22:24
  • @Neil Lunn: I know `.on('error')` gets reached when the stream is "broken" . But is it also reached when an error is returned by a function (`doc.save`) called inside `.on('stream')` callback ? – MarcoS Jun 07 '17 at 12:24

0 Answers0