Xihao
Xihao

Reputation: 122

MongoDB how to rollback or destroy the newly created collection in transaction

The problem I am trying to solve is in order to create collection foo, I need to add the user request data to bar. (If bar doesn't exist, create bar, else insert the data to bar.) Next, I want to pass bar's objectID to foo's field so that I can reference bar and create foo.

But if I first create bar success, then I try to create foo but it fails, I want to destroy the newly created bar. But, if bar exists before, then I only want to remove the added data from bar.

I tried to add these operations into a transaction, but MongoDB doesn't allow manipulating newly collection inside a transaction according the documentation:

Within a transaction, you can only specify read and write (CRUD) operations on existing collections. For example, a multi-document transaction cannot include an insert operation that would result in the creation of a new collection.

What is a better approach to solving this problem?

Upvotes: 1

Views: 482

Answers (1)

Xihao
Xihao

Reputation: 122

Yes, I should create the empty corrections foo and bar first, and it solves my problem.

Upvotes: 1

Related Questions