Skip to content

[BUG] update() raises a RevisionIdWasChanged when expecting a DuplicateKeyError #1057

@NiziL

Description

@NiziL

Describe the bug

When creating a Document with an unique indexed attribute, violating the uniqueness raise a RevisionIdWasChanged instead of a DuplicateKeyError.

To Reproduce

import asyncio
from typing import Annotated

import pymongo
from beanie import Document, Indexed, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient


client = AsyncIOMotorClient("mongodb://localhost:27017/test")


class MyDocument(Document):
    unique: Annotated[str, Indexed(index_type=pymongo.TEXT, unique=True)]


async def test():
    await init_beanie(client.get_default_database(), document_models=[MyDocument])
    doc = MyDocument(unique="test")
    await doc.save()
    doc2 = MyDocument(unique="test")
    await doc2.save()


if __name__ == "__main__":
    asyncio.run(test())

Expected behavior
Raise the DuplicateKeyError instead of replacing it by a RevisionIdWasChanged.

Additional context
The bug comes from documents.py, line 739/740.

I feel like we could easily catch the error, ensure the DuplicateKeyError comes from a revision id issue, and either raise a RevisionIdWasChanged or this error.
Something like:

except DuplicateKeyError as e:
    raise RevisionIdWasChanged if "revision_id" in str(e) else e 

I can prepare a PR for this, I just feel like my solution is a bit hacky right now... Any ideas ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions