save_condition's User Guide documentation perhaps misleading?
Hi guys,
As usual, I hope I am not missing something so apologies in advance if I did.
To keep the story short the User Guide http://docs.mongoengine.org/guide/querying.html#atomic-updates says that operators such 'add_to_set' can be used with save() as long as save_condition is present.
After a couple of runs I realised that I can't used save_condition with modifiers but only with operators. For example when trying to use
mytest.save(save_condition={'add_to_set_myfield':[1,1,2]}
I was getting all the time:
mongoengine.errors.InvalidQueryError: Cannot resolve field "add_to_set"
Then I checked the save() method and saw that 'save_condition' is transformed into a query as shown on https://github.com/MongoEngine/mongoengine/blob/master/mongoengine/document.py#L482
I then tracked down transform.query at https://github.com/MongoEngine/mongoengine/blob/master/mongoengine/queryset/transform.py#L46 where I realised that only operators are allowed.
I was trying to update a record if and only if an underlying listfield is unique at saving time hence that when I read the doc I thought it could be done this way.
By the way on another matter, on the API Reference documentation http://docs.mongoengine.org/apireference.html#mongoengine.Document.save it would be great to add a line saying something like:
'force_insert' and 'save_condition' are incompatible as the former only applies to inserts while the latter on updates
This seems obvious for those who has been playing for a while with MongoEngine and MongoDB but for those who are new, it saves plenty of deduction time... And perhaps just raising an Exception at the beginning of the save() method
An additional note is that I achieved what I wanted by other means using atomic updates and the add_to_set modifier. I created a mixin class inheriting from mongoengine.Document providing 'save' and 'save_with_uniqueness methods' so that all classes that have a listfield that require uniqueness will inherit from the mixin class.
If anyone needs some code I'm happy to post it. I just don't want to mislead the purpose of this thread.
An additional note is that I achieved what I wanted by other means using atomic updates and the add_to_set modifier. I created a mixin class inheriting from mongoengine.Document providing 'save' and 'save_with_uniqueness methods' so that all classes that have a listfield that require uniqueness will inherit from the mixin class.
If anyone needs some code I'm happy to post it. I just don't want to mislead the purpose of this thread.
do reference the code