BeanieODM / beanie

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

[BUG] AttributeError while Trying to use operator without making init_beanie call #994

Closed nimblecopilot13 closed 2 months ago

nimblecopilot13 commented 3 months ago

Describe the bug Beanie find near operator is giving an AttributeError, if not made the init_beanie call.

AttributeError: geo. Did you mean: 'get'?

I am using the same code as the document: https://beanie-odm.dev/api-documentation/operators/find/#near

To Reproduce

class GeoObject(BaseModel):
    type: str = "Point"
    coordinates: Tuple[float, float]

class Place(Document):
    geo: GeoObject

    class Collection:
        name = "places"
        indexes = [
            [("geo", pymongo.GEOSPHERE)],  # GEO index
        ]

Near(Place.geo, 1.2345, 2.3456, min_distance=500)

Expected behavior

Should response the query

Additional context I am trying to make inter-servcice communication and generate the query from one service while the model and server are on another.

init_beanie call is made on the server and working like a charm. Now I want to make a generic query processor and it looks like beanie has a good one, but I am unable to use the models from the client service as no init_beanie is called.

Can any of you please suggest any solution of the problem.

Version

07pepa commented 2 months ago

This is expected you must call innit beane to establish what mongoversion you are calling and even connection to mongo

this is similar like other orm works and is not a bug

staticxterm commented 1 month ago

To add onto 07pepa's answer, this is not strictly ORM/ODM related. This is Pydantic related. You could not even do for example GeoObject.type since Pydantic does not allow this. You can access class members once you instantiate the class, since Pydantic needs to take care of all of the validation and so on. Beanie does some magic(1) in its init_beanie() call to enable this usage for those operators, so init_beanie() must always be called.

(1) Basically the Beanie init_document_fields() helper method calls setattr(cls, k, ExpressionField(path)) which adds every model field to the class as an ExpressionField that basically transforms every named attribute to its string representation.