0

I am trying to ensure name uniqueness in a MongoAlchemy-backed model, and am uncertain how to go about it.

My first attempt involved writing a wrap validator which checked for existing database entries with the same name and checked against them (to ensure that there were either 0 or 1 entries with the same name), but this failed because the validator only receives the string with the name, not the entire object (so comparing mongo_ids was impossible).

What's the best way to ensure that objects of a single class all have unique names?

kronosapiens
  • 1,333
  • 1
  • 10
  • 19

1 Answers1

2

You should use a unique index.

http://www.mongoalchemy.org/api/schema/document.html#mongoalchemy.document.Index

>>> class Person(Document):
...     name = StringField()
...     name_index = Index().ascending('name').unique()

The database will enforce the constraint for you. It's just wrapping the code that mongo already has here:

http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

Jeff Jenkins
  • 158
  • 1
  • 3