Mongoose bulkWrite upsert

Mongoose bulkWrite upsert

Here is a code snippet for a bulk update with upsert using Mongoose:

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');
    res.send('OK')
  })
  .catch( err => {
    console.log('BULK update error');
    res.status(500)
  });