Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk deleting documents from aggregate

I am trying to use a bulk delete on the results of a mongoose aggregate query.

var bulk = Collection.collection.initializeUnorderedBulkOp();
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec();

cursor.each(function(error, doc){
  if(doc){
    console.log(doc);
    bulk.find({_id : doc._id}).removeOne();
  }
});

if(bulk.length > 0) {
  bulk.execute(function(error){
    if(error){
      console.error(error);
      callback(error);
    }else{
      console.log(bulk.length + " documents deleted");
      callback(null);
    }
  });
} else {
  console.log("no documents to delete");
  callback(null);
}

This results in the "no documents to delete" being printed before the results of the aggregate in the each loop. Normally I would expect there to be a callback function for a database operation. I have tried adding a callback function to the params of exec, but the function never gets hit:

var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec(function(error, result){
  console.log(error);
  console.log(result);
  callback();
});
like image 453
Carasel Avatar asked Sep 29 '17 11:09

Carasel


1 Answers

Listen to the data and end events on the cursor:

cursor.on( 'data', function( data ) {
    bulk.find( { "_id" : data._id } ).removeOne();
});

cursor.on( 'end', function() {
    if ( bulk.length === 0 ) {
        callback();
    } else {
        bulk.execute(function (error) {
            if (error) {
                callback(error);
            } else {
                callback();
            }
        });
    }
});
like image 197
Carasel Avatar answered Sep 20 '22 23:09

Carasel