Skip to content

Delete document in transaction #8211

@HaoCherHong

Description

@HaoCherHong

In mongoose 5.7.3, seems there is no session option (or any option) on Model.remove API.
So how do I remove a document with condition in a transaction in mongoose?

Though I can do find a document first, then call Model.prototype.remove. But it would becomes 2 query to make, the problem is, document may be mutate between the 2 queries, which cause data inconsistency.

For example
0. Do something in transaction

  1. Query the doc in transaction with { a: 1 }
  2. (somebody else update the document outside of transaction to {a: 2} )
  3. call doc.remove()
  4. Do something in transaction
  5. Commit transaction

If I'm correct, the transaction would succeed without error and the document will be deleted, which is unwanted.

If there we can use session in Model.remove, we can just call Model.remove(condition, {session}) and verify the nRemoved to get rid of the unwanted behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new feature

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions