mongoengine: document.update(**kwargs) writes to MongoDB but not updating fields of document

Seems like batch updating with document.update(**kwargs) only affects DB, not current document. Here is an example:

from mongoengine import *

connect("test")


class SomeDocument(Document):
    title = StringField()

    def __unicode__(self):
        return self.title


SomeDocument.drop_collection()

doc = SomeDocument(title="Initial title")
doc.save()

print "Updating fields one by one and finally save()"
doc = SomeDocument.objects[0]
doc.title = "New title 1"
doc.save()
doc_reloaded = SomeDocument.objects[0]
print "Saved: %s, Loaded: %s" % (doc, doc_reloaded)

print ""

print "Batch updating with document.update(**kwargs)"
doc = SomeDocument.objects[0]
doc.update(**{ "set__title": "New title 2" })
doc_reloaded = SomeDocument.objects[0]
print "Saved: %s, Loaded: %s" % (doc, doc_reloaded)

Output

Updating fields one by one and finally save()
Saved: New title 1, Loaded: New title 1

Updating with update()
Saved: New title 1, Loaded: New title 2

Expected behaviour is to update field’s values after performing update().

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Reactions: 5
  • Comments: 15 (8 by maintainers)

Most upvoted comments

At least mention this unexpected behavior in the docs!

I just want to get my thoughts down about this issue before I forget them.

I think for our next major version we need to have a discussion around exactly how we store / save / retrieve data from the database. For example, as of today, we have save, update, and modify for writing to the database.

In my opinion it has become a little confusing for a user to know when to use what update method and exactly what impact it has on MongoEngine cached data.

This is certainly a bug. MongoEngine should retrieve the object every time instead of using the cache. If you want to invalidate parts of the cache that’s just fine but I prefer correct behaviour over optimizations. @rozza I’m reopening since this is a major issue and someone might want to pick it up (maybe me).