beanie icon indicating copy to clipboard operation
beanie copied to clipboard

Validation error when getting the doc and it's linked document is deleted.

Open runetech0 opened this issue 3 years ago • 2 comments

I have looked on the docs and according to docs "If a direct link is referred to a non-existent document, after the fetching it will stay the object of the Link class." But in my case it's raising ValidationError when the Linked document is deleted. Here is a sample of my code.\

`class User(Document):
        id: int
        invited_by: typing.Union[Link["User"], None] = None`

`async def test_sth(db: UsersDB):
          user1 = User(id=12)
          await user1.insert()
          user2 = User(id=123, invited_by=user1)
          await user2.insert()
          await user1.delete()
          await User.find_one(User.id == int(12), fetch_links=True)
    `

and it raises the following error. I don't know what I'm doing wrong or if there is a problem with my code.

` E   pydantic.error_wrappers.ValidationError: 1 validation error for User
  E   invited_by
  E     value is not a valid dict (type=type_error.dict)
  pydantic/main.py:331: ValidationError

`

runetech0 avatar Jan 16 '22 19:01 runetech0

Hey @rehmanali1337 , Thank you for the issue. I'll check this.

roman-right avatar Jan 25 '22 10:01 roman-right

嘿@rehmanali1337, 谢谢你的问题。我会检查这个。

i think ,when user is delete ,the Link can return None and update user

My solution is, when await ref_obj.fetch() return is Link , return None

image

but , I think there should be a better solution

douyahu avatar Feb 16 '22 05:02 douyahu

It looks like it was fixed.

Here is the code example:

import asyncio
import typing
import motor.motor_asyncio

from beanie import Document, Link, init_beanie


class User(Document):
    id: int
    invited_by: typing.Union[Link["User"], None] = None


async def test_sth():
    cli = motor.motor_asyncio.AsyncIOMotorClient(
        "mongodb://beanie:beanie@localhost:27017")
    db = cli["test_empty_link"]
    await init_beanie(db, document_models=[User])
    await User.delete_all()
    user1 = User(id=12)
    await user1.insert()
    user2 = User(id=123, invited_by=user1)
    await user2.insert()
    await user1.delete()
    res = await User.find_one(User.id == int(123), fetch_links=True)
    print(res)


asyncio.run(test_sth())

If the problem still exists feel free to reopen the issue

roman-right avatar May 23 '23 18:05 roman-right