Molitoris
Molitoris

Reputation: 1045

What is the proper way to define the collection name at the application startup with MongoEngine?

I use MongoEngine as an ODM in my Flask application. Depending on the passed configuration document, MongoEngine should use a different collection.

At the moment I achieve this by changing the internal meta variable model._meta['collection']. Is there an alternative for selecting the collection?

from mongoengine import connect
from api_service.model import MyModel


create_app(config):

app = Flask(__name__)

# load app.config 

connect(app.config['MONGODB_DB'],
        host=app.config['MONGODB_HOST'],
        port=app.config['MONGODB_PORT'],
        username=app.config['MONGODB_USERNAME'],
        password=app.config['MONGODB_PASSWORD'],
        )



MyModel._meta['collection'] = app.config['MONGODB_MYMODEL_COLLECTION']

I know that you can define the collection by meta:{} in the class body of the model (see here). But I am not in the app context there and therefore I cannot access `app.config'.

Upvotes: 1

Views: 326

Answers (1)

Radwan Abu-Odeh
Radwan Abu-Odeh

Reputation: 2065

You can simply modify the meta attribute inside the class itself

class MyModel(Document):
    meta = {"collection": "my_actual_collection_name"}
    ...

Check This for more meta attributes you can use


Solution Update

I defined a helper class that can have a provide an access the application's configurations

class AppConfigHelper:
    from flask import current_app
    APP_CONFIG = current_app.config

and in the document import and use that class to get the collection name.

class MyModel(Document):
    meta = {'collection': AppConfigHelper.APP_CONFIG['MONGODB_MYMODEL_COLLECTION']}
    ...

This is not the best solution I can think of, but it does the job.


Caution: this is not gonna work if you run it separately from Flask, it is going to crash, you can run it inside the app itself, or using flask shell

Upvotes: 1

Related Questions