The best place to call your ensure_index
calls is somewhere before you call run()
in your flash application. You want to make sure that your indexes are installed before you try to service any requests, because creating an index while the site is running will be very irrelevant. The error you get is related to the fact that you need the application context. Try:
app = Flask(__name__) mongo = PyMongo(app) if __name__ == '__main__': with app.app_context(): mongo.db.court.ensure_index( [("name", ASCENDING), ("slug", ASCENDING)], unique=True ) app.run()
As @thkang said, you should use a unique index to ensure that two documents do not have the same value for a field or set of fields taken together. Learn more about this and the pymongo ensure_index
syntax in pymongo docs .
source share