GaddBox
GaddBox

Reputation: 412

Mongoose Node - Request Multiple updates to multi documents with success all or cancel all?

Good question I expect to be slane down quickly.

Sometimes we want to update many documents when an action is performed at the front end.

Example React Code

this.props.submitRecord(newRecord, (err, record) => {
  if (err) actions.showSnackBar(err);
  else {
    actions.showSnackBar("Record Submitted Successfully ...");
    this.props.validateClub(this.props.club._id, (err, message) => {
      if (err) actions.showSnackBar(err);
      else {
        obj.setState({
          player: {},
          open: false
        });
        actions.showSnackBar(message);
      }
    });
  }
});

As we can see I firstly submit the first request, and on success, I submit the second request. If the first fails, the second one won't happen. But, if the first one passes, and the second one fails for whatever reason, we have a data mismatch.

Ideally, we want to send them all together and they all pass or none pass. Is there a simple way at doing this with react, Node and mongoose or do I have to do it the hard way (Which is also subject to error been possible, store old values until all request are satisfied, or make some revert request on the node server, lol).

Thanks

Upvotes: 1

Views: 299

Answers (1)

Mustehssun Iqbal
Mustehssun Iqbal

Reputation: 566

Transactions are a part of Mongodb 4.0. There was no transaction support in Mongodb in the previous versions. The other way could be to perform rollback on failure through code, and there are some non-opinionated npm packages such as mongoose-transaction.

https://www.mongodb.com/transactions

Upvotes: 1

Related Questions