Is there a Mongoose method to save multiple documents, but only when all success

Viewed 496

I have an array of documents, but I only want to save them when every document will success. Is there a Method from Mongoose?

Something like:

Insert el[0] - success
Insert el[1] - success
Insert el[2] - fail
Delete el[1]
Delete el[0]
1 Answers

You can use transactions to implement this. Here's an example from the docs:

let session = null;
return Customer.createCollection().
  then(() => Customer.startSession()).
  then(_session => {
    session = _session;
    session.startTransaction();
    return Customer.create([{ name: 'Test' }], { session: session });
  }).
  then(() => Customer.create([{ name: 'Test2' }], { session: session })).
  then(() => session.abortTransaction()).
  then(() => Customer.countDocuments()).
  then(count => assert.strictEqual(count, 0)).
  then(() => session.endSession());

You can use abortTransaction to rollback queries in case of error.

Read more here: https://mongoosejs.com/docs/transactions.html https://www.mongodb.com/transactions

Related