BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.99k stars 211 forks source link

[BUG] insert/replace_many not triggers actions #431

Closed Rubikoid closed 1 year ago

Rubikoid commented 1 year ago

Describe the bug Inserting/replacing documents using insert_many or replace_many not triggers any of event-based actions.

To Reproduce

import asyncio
from typing import cast

from beanie import Document, Insert, Replace, before_event, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient

class Test(Document):
    name: str

    @before_event([Insert, Replace])
    def name_force_upper(self) -> None:
        self.name = self.name.upper()

async def test():
    client = AsyncIOMotorClient("mongodb://root:root@localhost:27017")

    # drop db...
    await client.drop_database("test_db")

    await init_beanie(database=client.test_db, document_models=[Test])

    test_doc = Test(name="lowcase_string")
    await test_doc.insert_many([test_doc])

    test_from_db = cast(Test, await Test.find_one())
    assert test_doc.name.upper() == test_from_db.name, f"{test_doc.name = }, {test_from_db.name = }"

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

Expected behavior test_from_db.name in uppercase, which means, that name_force_upper were called

Additional context This behaviour not described in docs, and there are no issues about it, so i think this is a bug.

roman-right commented 1 year ago

Hi @Rubikoid , There are no events for replace_many or insert_many as these operations are not methods of objects, but class methods. But I'll this about this feature, thank you.

hd10180 commented 1 year ago

same problem here, i have to process the document field before call insert_many