Cleanly catching NotUniqueErrors with fields

176 views
Skip to first unread message

James Clemence

unread,
Mar 17, 2013, 8:41:20 AM3/17/13
to mongoeng...@googlegroups.com
So,

I have a fairly simple model which constrains on a particular owner only having a monkey with one name:

    class Monkey(mongoengine.Document):
        name = mongoengine.StringField(unique_with='owner')
        owner = mongoengine.ReferenceField(User)

This works fine to enforce the constraint, however I then have issues in the following situation. When I try to insert a second Monkey for the same user with the same name, I get a NotUniqueError, however this gives me a broad message, and doesn't enable me to analyse which field raised the error

NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error index: test.feed.$name_1_owner_1 dup key: { : "Bob", : { $ref: "user", $id: ObjectId('5145b8a28dd4ff1c5281d151') } })

I can of course parse the error message for the offending issue, discovering that test.feed.$name_1_owner_1 was the issue, and then pass on a nicer error message to the client, however this seems quite clunky. Is there a way to catch this exception on a per-field basis?

Thanks!

Ross Lawley

unread,
Mar 19, 2013, 6:07:33 AM3/19/13
to mongoeng...@googlegroups.com
Hi,

The error is coming back because its the index that is catching and throwing back the error, currently just the raw error is thrown.  Perhaps a cleaner exception could be raised, if you can write a parser that will cleanly identify the fields then, I'd be happy to add that to mongoengine.

Ross


--
You received this message because you are subscribed to the Google Groups "MongoEngine Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoengine-us...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages