graphql-python/graphene-mongo

When a db_alias is explicitly given, graphene-mongo always uses default value with MongoengineConnectionField

lcastiglione opened this issue · 1 comments

Hi! When I define my own db_alias, it always ends up choosing default when using MongoengineConnectionField. For example:

connect("test",
             alias="stocks",
             host=127.0.0.1,
             port=27017,
             username="user",
             password="password",
             authentication_source="admin")

class TitleModel(Document):
    meta = {'collection': 'titles', "db_alias": "stocks"}

class TitleQuery(ObjectType):
    titles = MongoengineConnectionField(TitleType)

If I run the following graphql command:

query getTitle($symbol: String) {
  titles(symbol: $symbol) {
    edges {
      node {
        id
        symbol
        sector
        name
      }
    }

It returns this error message:

{
  "fatalErrors": [
    {
      "message": "You have not defined a default connection",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "titles"
      ]
    }
  ],
  "data": {
    "titles": null
  }
}

Doing research I came across this line in the file fields.py

The problem is that mongoengine.get_db() expects the alias parameter. If it does not receive it, it uses the default.

As a solution, I propose to change that line from this:

count = await sync_to_async(
                         (mongoengine.get_db()[self.model._get_collection_name()]).count_documents,
                         thread_sensitive=False,
                         executor=ThreadPoolExecutor())(args_copy)

to this:

count = await sync_to_async(
                         (mongoengine.get_db(alias=self.model._meta["db_alias"])[self.model._get_collection_name()]).count_documents,
                         thread_sensitive=False,
                         executor=ThreadPoolExecutor())(args_copy)

Exception handling remains but I think it's a good starting point. Thks!

I just saw that they already fixed this in version 0.3.0.

Sorry for the inconvenience and thank you very much for the work!