-1

i'm making a many insert in node using bulk upsert, and I get some code references from related links bulk upsert, and this is the code

  var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 mongoose.connect('mongodb://localhost/test');

 var sampleSchema  = new Schema({},{ "strict": false });

 var Sample = mongoose.model( "Sample", sampleSchema, "sample" );

 mongoose.connection.on("open", function(err,conn) { 

    var bulk = Sample.collection.initializeOrderedBulkOp();
    var counter = 0;

    // representing a long loop
    for ( var x = 0; x < 100000; x++ ) {

        bulk.find(/* some search */).upsert().updateOne(
            /* update conditions */
        });
        counter++;

        if ( counter % 1000 == 0 )
            bulk.execute(function(err,result) {             
                bulk = Sample.collection.initializeOrderedBulkOp();
            });
    }

    if ( counter % 1000 != 0 )
        bulk.execute(function(err,result) {
           // maybe do something with result
        });

 });

and the code is right there is nothing wrong, but I still do not understand about some code below

if ( counter % 1000 == 0 )
            bulk.execute(function(err,result) {             
                bulk = Sample.collection.initializeOrderedBulkOp();
            });

what is the purpose of this condition? if ( counter % 1000 == 0 ) ?

Omlegron
  • 1
  • 1

1 Answers1

0

This evaluates whether counter is a multiple of 1,000. More accurately, evaluates whether counter / 1000 is equal to 0. See Arithmetic Operators.

Because this script is executing bulk operations, it is only executing batches of 1,000. This condition enforces that.

Fissure King
  • 1,250
  • 7
  • 17
  • @Omlegron If that solved your issue, would you mind voting and accepting the answer so that others may benefit from it as well. – Fissure King Dec 01 '17 at 01:53