Home > OS >  Save two different documents simultaneously within the single route
Save two different documents simultaneously within the single route

Time:12-25

I'm building a social media app using MERN stack in which I have a model of connections for every user. And I'm also using mongoose.

The connection model is having the details of the other user to which a user is connected and same for the other user. Like A's connection document has details of B and B's connection document has details of A.

So, I have a route like api/connections/acceptrequest/:user_id, so that the user can connect with other user by accepting request. I wrote the logic to update the documents of both users but my query is:

As I want to save changes for both documents, I need to do await connection.save() and await senderConnection.save() simultaneously, so is it ok? Because my concern is what if first document gets saved and other might get some error and it does'nt get saved.

Is there any other practical way?

CodePudding user response:

There's probably a different way to store this relationship in your documents, but without knowing your design, etc. if your concern is about how to handle multiple related updates at the same time I'd suggest using a MongoDB Transaction.

Mongoose has support for MongoDB Transactions as laid out in their docs:

Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails.

Though, as I started off with you might also want to think about if you should change your document structure instead, as the MongoDB docs say:

In MongoDB, an operation on a single document is atomic. Because you can use embedded documents and arrays to capture relationships between data in a single document structure instead of normalizing across multiple documents and collections, this single-document atomicity obviates the need for multi-document transactions for many practical use cases.

Either way, a Transaction should solve the issues you are concerned about.

  • Related