0

I'm creating a wrapper to solve all my connections with mongoengine, so I created a function that reads mongoDB configuration from a file and connects to it.

Thee function looks like this:

def connect_mongo_odm(config_file_location, db_name):
    if db_name:
        base_path = ['databases', db_name]
        conf_specs = {
            'host': {
                'path': base_path + ['host']
            },
            'port': {
                'path': base_path + ['port']
        }
    }

    fileConfiguration = dao_utils.readConfiguration(config_file_location, conf_specs)

    auth = None
    host = fileConfiguration.get('host', None)

    host = "mongodb://" + host

    connect(alias=db_name,
            host=host,
            socketKeepAlive=True, socketTimeoutMS=30000)

And I use it as:

# import previous function
# This is another module in my application
connect_mongo_odm('/path/to/config/file', 'dbName')

But When I try to save a document I get an exception saying that I have no default connection defined.

rafaelleru
  • 367
  • 1
  • 2
  • 19
  • Do your document definitions have a `meta` attribute specifying the connection alias that they are supposed to use, e.g. `meta = {'db_alias': 'dbName'}`? You give your connection an alias that is not `'default'` in `connect_mongo_odm`. If your documents don't have that meta attribute, they will try to use a connection aliased `'default'`, which apparently is not created in your case. – shmee Jan 15 '19 at 11:37
  • No, the documents have no 'db_alias' attribute but I tried to set meta = {'db_alias': db_name} and still it does not work. @shmee – rafaelleru Jan 15 '19 at 14:44
  • Do you still get the same error? And you seem to be using `db_name` as a variable in that `meta` attribute. When and where do you set it in that context? – shmee Jan 16 '19 at 06:41
  • In the Document declaration, I added `meta={'db_alias': dbName}` but it doesn't work. @shmee – rafaelleru Jan 16 '19 at 08:16
  • In your previous comment it was `db_name`, now you say it is `dbName`. Which of the two is true? Apart from that, you use them without quotes, which makes them variables, instead of the string I had in my example. In the end, what matters is that the alias given to the connection and the value given to meta's db_alias key have the same value. Also, _it does not work_ isn't helpful. Please share the exact error and where it occurs . – shmee Jan 16 '19 at 08:31

1 Answers1

0

You need to define meta = {"db_alias": "your_connection_alias"} in each of your Document classes. If you don't set it, it will use the "default" alias.

See here for an example: https://stackoverflow.com/a/56434241/6203472

bagerard
  • 5,681
  • 3
  • 24
  • 48