pythonmongodbmongokit

mongokit No collection found


I'm using mongokit with flask, and everytime I try to use a collection I created, I receive the error No collection found

I defined my collections in a separated file models.py. It looks like this:

from mongokit import Connection, Document
import os
import sys

here = os.path.dirname(os.path.abspath(__file__))
path = os.path.abspath(os.path.join(here, 'settings'))
sys.path.append(path)
from settings import base as settings

connection = Connection()

@connection.register
class Contact(Document):
    __database__ = settings.MONGO_DBNAME
    __collection__ = "Contact"

    structure = {
        "name":unicode,
        "mobile_number":unicode,
    }

    required_fields = ["name"]


@connection.register
class User(Document):
    __database__ = settings.MONGO_DBNAME
    __collection__ = 'User'

    structure = {
        "username":unicode,
        "twitter_access_token":unicode,
        "twitter_token_secret":unicode,
        "contacts":[Contact]
    }
    required_fields = ["username"]
    default_values = {
            "twitter_access_token": "",
            "twitter_token_secret": ""
        }

But then I tried:

>>> from models import User
>>> u = User()
>>> u["username"] = "somename"
>>> u.save()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/fernandocezar/.virtualenvs/contacts/lib/python2.7/site-packages/mongokit/document.py", line 404, in save
    self.validate(auto_migrate=False)
  File "/Users/fernandocezar/.virtualenvs/contacts/lib/python2.7/site-packages/mongokit/document.py", line 230, in validate
    (size_limit, size_limit_str) = self._get_size_limit()
  File "/Users/fernandocezar/.virtualenvs/contacts/lib/python2.7/site-packages/mongokit/document.py", line 214, in _get_size_limit
    server_version = tuple(self.connection.server_info()['version'].split("."))
  File "/Users/fernandocezar/.virtualenvs/contacts/lib/python2.7/site-packages/mongokit/document.py", line 622, in __getattribute__
    raise ConnectionError('No collection found') 
mongokit.mongo_exceptions.ConnectionError: No collection found

I followed this tutorial, but not even the notation connection.<dbname>.<collection>() works. And yes, there is, indeed, such a collection.

What am I missing?


Solution

  • To quote the tutorial you linked:

    To avoid repeating ourselves though, let’s specify the database and collection name in the Document definition:

    @connection.register
    class BlogPost(Document):
        __collection__ = 'blog_posts'
        __database__ = 'blog'
        structure = {...}
    
    >>> bp = connection.BlogPost()
    

    In the shell example, the model object is constructed through the connection object. In your case, you were simply doing user = User(). Try creating the user through the same connection instance that you used to register the model (e.g. user = connection.User()).