Search code examples
mongoengineflask-mongoengine

Mongoengine Link to Existing Collection


I'm working with Flask/Mongoengine-MongoDB for my latest web application.

I'm familiar with Pymongo, but I'm new to object-document mappers like Mongoengine.

I have a database and collection set up already, and I basically just want to query it and return the corresponding object. Here's a look at my models.py...

from app import db

# ----------------------------------------
# Taking steps towards a working backend.
# ----------------------------------------

class Property(db.Document):

    # Document variables.
    total_annual_rates = db.IntField()
    land_value = db.IntField()
    land_area = db.IntField()
    assessment_number = db.StringField(max_length=255, required=True)
    address =  db.StringField(max_length=255, required=True)
    current_capital_value = db.IntField
    valuation_as_at_date = db.StringField(max_length=255, required=True)
    legal_description = db.StringField(max_length=255, required=True)
    capital_value = db.IntField()
    annual_value = db.StringField(max_length=255, required=True)
    certificate_of_title_number = db.StringField(max_length=255, required=True)

    def __repr__(self):
        return address

    def get_property_from_db(self, query_string):
        if not query_string:
            raise ValueError()
        # Ultra-simple search for the moment.
        properties_found = Property.objects(address=query_string)
        return properties_found[0]

The error I get is as follows: IndexError: no such item for Cursor instance

This makes complete sense, since the object isn't pointing at any collection. Despite trolling through the docs for a while, I still have no idea how to do this.

Do any of you know how I could appropriately link up my Property class to my already extant database and collection?


Solution

  • The way to link a class to an existing collection can be accomplished as such, using meta:

    class Person(db.DynamicDocument):
    
        # Meta variables.
        meta = {
            'collection': 'properties'
        }
    
        # Document variables.
        name = db.StringField()
        age = db.IntField()
    

    Then, when using the class object, one can actually make use of this functionality as might be expected with MongoEngine:

    desired_documents = Person.objects(name="John Smith")
    john = desired_documents[0]
    

    Or something similar :) Hope this helps!