BeanieODM / beanie

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

[BUG] Insert many doesn't update id #382

Closed niklass-l closed 1 year ago

niklass-l commented 1 year ago

Describe the bug Model.insertMany([model, model]) does not update the ids, unlike model.insert()

To Reproduce

from beanie import Document, Link, Indexed, init_beanie
from typing import ForwardRef
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient

class Message(Document):
    content: str

class Ticket(Document):
    messages: list[Link[Message]]

client = AsyncIOMotorClient()

async def init():
    await init_beanie(connection_string=db_uri,
                      document_models=[Message, Ticket])

async def add():
    await init()

    message_one = Message(content="message one")
    message_two = Message(content="message two")

    await Message.insert_many([message_one, message_two])

    print(message_one.id)  # None
    print(message_two.id)  # None

    message_three = Message(content="message three")
    await message_three.insert()
    print(message_three.id)  # 63501dcd96bab08ee232c702

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

Expected behavior All models in the list should be updated with their given id

jakubmatyszewski commented 1 year ago

await Message.insert_many([message_one, message_two]) is an operation called on Message object, performs insertion to collection and return ObjectIds. See how function works here.

message_one = Message(content="message one")
message_two = Message(content="message two")
output = await Message.insert_many([message_one, message_two])
print(output) # [ObjectId('63544f3cafe4c6e50c3e22c5'), ObjectId('63544f3cafe4c6e50c3e22c6')]

On the other hand, await message_three.insert() is called directly on message_three object and if you see how this function is implemented, you'll see that it grabs result id and assigns it to self, then returns self.

All in all, my point is that the function insert_many doesn't perform any changes on provided variables, thus it seems like correct behaviour, not a bug.

niklass-l commented 1 year ago

Good argument, I agree with you. In any case updating the ids on the objects is trivial. Thank you for taking the time to reply :)

skar404 commented 1 year ago

Hello, thx for issue

I fink it a problem, because insert many result only ObjectId wise out object and original object nave None ObjectId. i need maping ObjectID with object :(

But insert one object updating ObjectId. This is different from multi insert.


@roman-right may be open issue and i fix it?

I have 2 plan:

  1. update original object
  2. return new object with ObjectId

Thx for see ヽ(´▽`)/