flask_mongoengine

from flask_mongoengine import MongoEngine

Mongoengine is a Document-Object Mapper (think ORM, but for document databases)

Easy access to database collections and enforced schema

Uses pymongo under the surface

Setup

db = MongoEngine() #Database connection data in config

db.init_app(app) # In create app factory

Config

You need to define the host, the /after the url can say the db name

class DevelopmentConfig(Config):
    DEBUG=True
    #Mongoengine Variables
    MONGODB_HOST='mongodb://[username]:[password]@ds014648.mlab.com:14648/wissen'

app.config.from_object(config[config_name])
config[config_name].init_app(app)

Making Models

Potential Field

Schema

Derive from EmbeddedDocument(embed in other docs), Document, or DynamicDocument(any fields will be saved)

Connecting Models

EmbeddedDocumentField includes the object in the model

ReferenceField can be used to include reference ids that are lazily dereferenced on access

Creation

An id is created automatically on save: profile.id , convert to string with str(profile.id)

Set id by adding primary_key=True to Field and it will be aliased to id

Images Add Photo

Retrieve Img

img = Image.objects()[0].img.read()

Query

You need to define and import the model

Operators

Double underscore after field to do operator

  • in – value is in list (a list of values should be provided)

Advanced

Last updated