MongoEngine/mongoengine

Mongoengine Connection Failure: You have not defined a default connection

BrayanMota opened this issue · 2 comments

Start a python project, using fastapi with mongoengine. Yesterday it was working normally, but today when running any method that has the connection to the database, the connection failure error occurs (mongoengine.connection.ConnectionFailure: You have not defined a default connection ).

My connection:

from mongoengine import connect

connect(db="mydb", host='localhost', port=27017, alias='default')

My models:

from mongoengine.document import Document
from mongoengine.fields import StringField, BooleanField, ListField, ReferenceField
from mongoengine import PULL


class Permissao(Document):
    permissao = StringField()


class Grupo(Document):
    grupo = StringField()
    
    permissoes = ListField(ReferenceField('Permissao', reverse_delete_rule=PULL))


class Usuario(Document):
    nome_usuario = StringField()
    ativo = BooleanField()
    senha = StringField()
    
    grupos = ListField(ReferenceField('Grupo', reverse_delete_rule=PULL))
    permissoes = ListField(ReferenceField('Permissao', reverse_delete_rule=PULL))

It worked, I switched the connection to the models and put a meta field, check it below:

from mongoengine.document import Document
from mongoengine.fields import StringField, BooleanField, ListField, ReferenceField
from mongoengine import PULL
from mongoengine import connect

connect(db="mydb", host="localhost", port=27017, alias="mydb-alias")

class Permissao(Document):
    permissao = StringField()

    meta = {"db_alias" : "mydb-alias" , "collection" : "permissao"}


class Grupo(Document):
    grupo = StringField()
    
    permissoes = ListField(ReferenceField('Permissao', reverse_delete_rule=PULL))
    
    meta = {"db_alias" : "mydb-alias" , "collection" : "grupo"}


class Usuario(Document):
    nome_usuario = StringField()
    ativo = BooleanField()
    senha = StringField()
    
    grupos = ListField(ReferenceField('Grupo', reverse_delete_rule=PULL))
    permissoes = ListField(ReferenceField('Permissao', reverse_delete_rule=PULL))

    meta = {"db_alias" : "mydb-alias" , "collection" : "usuario"}

It sounds like your call to connect was not being made in your initial version for whatever reason. The connection gets stored globally so it doesn't matter if you do it in the same file or not