Search code examples
javascriptnode.jsmongodbbulkupdate

MongoError: multi update only works with $ operators while using bulk find and update in node.js


Why getting error

MongoError: multi update only works with $ operators

while using bulk find and update to update multiple document.

Tried :

var bulk = db.collection('users').initializeUnorderedBulkOp();

var emails = ['[email protected]', '[email protected]', '[email protected]','[email protected]'];
var allStatus = ['s1', 's2', 's3', ''];

for (var i =0; i< allStatus.length; i++) {
  var query = { email: emails[i], status: { '$ne': allStatus[i] } };
  var updateField = {};
  if(allStatus[i]) {
      updateField = {
        $set: {status: allStatus[i], date: new Date()},
        $push: {
          notes: {note: 'jdf'+i, date: new Date()},
          history: {status: allStatus[i], date: new Date()}
        }
      };
  }
  bulk.find(query).update(updateField);
}

bulk.execute();

Solution

  • Finally I got what was the problem and solved that problem

    The error

    MongoError: multi update only works with $ operators

    occurred when updateField is empty object like updateField = {}. When I was trying to update a record with empty object then was getting this error for bulk update.

    so before pun into the bulk checked that the updateField is empty or not. put into the bulk operation if not empty object

    like:

    if(Object.keys(updateField).length) {
       bulk.find(query).update(updateField);
    }
    

    By this way I solved my problem