mongokit icon indicating copy to clipboard operation
mongokit copied to clipboard

unique index does not work

Open midnightradio opened this issue 12 years ago • 2 comments

On mongokit v0.7.2, documents can be saved with duplicated keys which has unique constraints.

This example is based on sample code shown in official documents.

from mongokit import *

class Movie(Document):
  __collection__ = 'mongokit'
  __database__ = 'test'
  structure = {
    'standard':unicode,
    'other':{
      'deep':unicode,
    },
    'alsoindexed':unicode,
  }
  indexes = [
    {
      'fields':'standard',
      'unique':True,
    },
    {
      'fields':['alsoindexed', 'other.deep']
    },
  ]

connection = Connection()
connection.register([Movie])

movie = connection.Movie()
movie['standard'] = u'testdeep'
movie['alsoindexed'] = u'indexed'
movie.save()

movie = connection.Movie()
movie['standard'] = u'test'
movie['other']['deep'] = u'testdeep'
movie['alsoindexed'] = u'indexed'
movie.save()

print connection.Movie.find({'standard':u'test'}).count()

this example prints out 2 as a result, which means producing duplicated records.

midnightradio avatar Jul 03 '12 12:07 midnightradio

I'm having a similar issue

class RootDocument(Document):
    __database__ = 'lockbox'

@connection.register
class User(RootDocument):
    __collection__ = "users"
    structure = {
        'username': basestring,
        'password': basestring,
        'projects': list,
        'owners': list,
        'created': datetime.datetime}

    required_fields = ['username', 'password']
    default_values = {
        'projects': [],
        'owners': []}

    indexes = [{
        'fields': ['username'],
        'unique': True,
        'check': False}]

And when I add 2 or more users with the same username it passes without error. Also in Mongo I don't see any indexes being created for that field.

gekitsuu avatar Sep 04 '12 17:09 gekitsuu

I know this is an older issue but in case anyone is searching for this info on this I figured it was worth a followup. Guessing this is due to the removal of the automatic ensure_index call that used to be in the Collection class. This was removed as of v0.7.1.

Here is the changelog entry: "fix #45 -- remove automatique index creation"

You can see the note and commented out code in the Collection class here: https://github.com/namlook/mongokit/blob/master/mongokit/collection.py#L46

The suggested approach now being to maintain some sort of utility script for generating indexes by hand (see https://groups.google.com/forum/?fromgroups=#!topic/mongokit/UMDJq0oxMBA). The Document class has a generate_index method that makes it pretty simple. I've added something like this recently to the whirlwind framework. https://github.com/trendrr/whirlwind/blob/master/whirlwind/bin/whirlwind-admin.py#L81

There is a bit of whirlwind specific code in it (that could be easily refactored out) but you should get the point.

mdennebaum avatar Oct 18 '12 15:10 mdennebaum