Mongoose bulk update upsert

Mongoose bulk update upsert

MongoDB's upsert option enables the creation of a new document if the query of an update operationdoesn't match any existing document. Basically, an update command with upsert creates a document if it does notexist already, and update it otherwise.

This operation is rather striaghtforward when updating single documents but can be trickier when applied to multiple documents at conce. For multiple documents, bulkWrite can be used:

let bulk_operations = []

for (var transaction of req.body.transactions) {
  bulk_operations.push({
    updateOne: {
      filter: transaction,
      update: transaction,
      upsert: true
    }
  })
}

Transaction.bulkWrite(bulk_operations)
.then( bulkWriteOpResult => {
  console.log('BULK update OK');
})
.catch( err => {
  console.log(err);
});