mongoengine.errors.InvalidQueryError: Cannot resolve field "id"

Viewed 649

In the update,and delete route,and now in Like and Dislike in the api (fastapi) it's giving the same error->mongoengine.errors.InvalidQueryError: Cannot resolve field "id",so to be simpler I'll just use Like as an example,the schema is

ps : if you're asking yourself,yes I already tried giving it id field and alias with _id and all possibilities that I could think

class Like(BaseModel):
    user_id: str
    post_id: str

The route is

@router.post("/like", status_code=201)
def like(like_data: schemas.Like, current_user: int = Depends(oauth2.get_current_user)):
    new_like = Likes()
    new_like.user_id = like_data.user_id
    post_of_the_like = Post.objects(_id=like_data.post_id)
    post_of_the_like.likes.append(new_like)
    post_of_the_like.save()

    return {"message": "successfully added like"}

and the model is

class Likes(mongoengine.EmbeddedDocument):
    user_id = mongoengine.ObjectIdField(required=True)

class Post(mongoengine.Document):
    _id = mongoengine.StringField(default=str(uuid.uuid4()),)

    title = mongoengine.StringField(required=True)
    content = mongoengine.StringField(required=True)

    published = mongoengine.BooleanField(required=True, default=True)
    created_at = mongoengine.DateTimeField(default=datetime.datetime.now)

    likes = mongoengine.EmbeddedDocumentListField(Likes)
    dislikes = mongoengine.EmbeddedDocumentListField(Dislikes)

    comments = mongoengine.EmbeddedDocumentListField(Comment)

    type = mongoengine.StringField(required=True, default="post")
    about = mongoengine.StringField(default="The creater did not put an about")
    tags = mongoengine.ListField(mongoengine.StringField())
    banner = mongoengine.StringField(required=False)

    meta = {
        "db_alias": "jc",
        "collection": "posts",
    }

and the whole message error is


Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\mongoengine\queryset\transform.py", line 91, in query
    fields = _doc_cls._lookup_field(parts)
  File "C:\Python39\lib\site-packages\mongoengine\base\document.py", line 1107, in _lookup_field
    raise LookUpError('Cannot resolve field "%s"' % field_name)
mongoengine.errors.LookUpError: Cannot resolve field "id"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "C:\Python39\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "C:\Python39\lib\site-packages\fastapi\applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "C:\Python39\lib\site-packages\starlette\applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:\Python39\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
    raise exc
  File "C:\Python39\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "C:\Python39\lib\site-packages\starlette\middleware\cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "C:\Python39\lib\site-packages\starlette\exceptions.py", line 82, in __call__
    raise exc
  File "C:\Python39\lib\site-packages\starlette\exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "C:\Python39\lib\site-packages\starlette\routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "C:\Python39\lib\site-packages\starlette\routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "C:\Python39\lib\site-packages\starlette\routing.py", line 61, in app
    response = await func(request)
  File "C:\Python39\lib\site-packages\fastapi\routing.py", line 216, in app
    solved_result = await solve_dependencies(
  File "C:\Python39\lib\site-packages\fastapi\dependencies\utils.py", line 527, in solve_dependencies
    solved = await run_in_threadpool(call, **sub_values)
  File "C:\Python39\lib\site-packages\starlette\concurrency.py", line 39, in run_in_threadpool
    return await anyio.to_thread.run_sync(func, *args)
  File "C:\Python39\lib\site-packages\anyio\to_thread.py", line 28, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,
  File "C:\Python39\lib\site-packages\anyio\_backends\_asyncio.py", line 805, in run_sync_in_worker_thread
    return await future
  File "C:\Python39\lib\site-packages\anyio\_backends\_asyncio.py", line 743, in run
    result = func(*args)
  File "C:\Users\invis\OneDrive\Área de Trabalho\jc_api\.\app\oauth2.py", line 40, in get_current_user
    user=User.objects(id=token_id).first()
  File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 290, in first
    result = queryset[0]
  File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 200, in __getitem__
    queryset._cursor[key],
  File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 1645, in _cursor
    self._cursor_obj = self._collection.find(self._query, **self._cursor_args)
  File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 1694, in _query
    self._mongo_query = self._query_obj.to_query(self._document)
  File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 91, in to_query
    query = query.accept(QueryCompilerVisitor(document))
  File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 184, in accept
    return visitor.visit_query(self)
  File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 80, in visit_query
    return transform.query(self.document, **query.query)
  File "C:\Python39\lib\site-packages\mongoengine\queryset\transform.py", line 93, in query
    raise InvalidQueryError(e)
mongoengine.errors.InvalidQueryError: Cannot resolve field "id"

If anyone could give a hint or opinion of what should help I would appreciate a lot,I searched through github but all examples are either flask or django and use methods that don't apply to this case,and even if you can't help,thanks for reading still here

1 Answers

Few things are wrong in your code snippet but hopefully you'll find the answer below:

class Post(mongoengine.Document):
    _id = mongoengine.StringField(default=str(uuid.uuid4()),)
  • unrelated with your problem but default should be a callable, otherwise it gets evaluated once and will return the same value all the time
  • You should avoid using "_id" to name your field, "_id" is something used internally by mongoengine.
  • Set primary_key=True on the key that is supposed to be the primary key (i.e what gets saved in the document as "_id" when translating MongoENgine -> pymongo document)

Typically your primary key should be defined like (below is the default id that gets defined if you don't provide one)

id = ObjectIdField(default=ObjectId, primary_key=True)
Related