title: How can I cancel MongoDB query from .each callback
body: <p>I implemented a little NodeJs web server that stores log entries and provides a backend for a web based log browser. The web interface provides also an "Export to CVS" function and lets user download the logs in CVS format. My code looks similar to this:</p>
  
  <pre><code>this.log_entries(function(err, collection) {
      collection.find(query)
          .sort({_id: 1})
          .each(function (err, doc) {
              if(doc){
                WriteLineToCSVFile(doc);
              }
              else {
                ZipCSVFileAndSendIt();
              }
          });
  });
  </code></pre>
  
  <p>The export operation may take a significant amount of time and disk space in case if a user didn't specify the right filters for the query. I need to implement a fail safe mechanism preventing this. One important requirement is that user should be able to abort the ongoing export operation at any point in time. Currently my solution is that I stop writing the data to the CSV file, however the callback passed to the <code>.each()</code> still gets called. I could not find any information how to stop the each loop. So the question is how can I do this?</p>
  
  <p><strong>UPDATE, THE ANSWER:</strong>
  Use <code>cursor.nextObject()</code>
  For the correct answer see the comments by @dbra below: <code>db.currentOp()</code> and <code>db.killOp()</code> doesn't work for this case.</p>
  
  <p>The final solution looks like this:</p>
  
  <pre><code>this.log_entries(function(err, collection) {
      var cursor = collection.find(query);
      cursor.sort("_id", 1, function(err, sorted) {
  
          function exportFinished(aborted) {
              ...
          }
  
          function processItem(err, doc) {
              if(doc === null ) {
                  exportFinished(false);
              }
              else if( abortCurrentExport ) {
                  exportFinished(true);
              }
              else {
                  var line = formatCSV(doc);
                  WriteFile(line);
                  process.nextTick(function(){
                      sorted.nextObject(processItem);
                  });
              }
          }
          sorted.nextObject(processItem);
      });
  });
  </code></pre>
  
  <p>Note the usage of <code>process.nextTick</code> - without it there will be a stack overflow!</p>