mongoengine
mongoengine copied to clipboard
Document.update() updates mongodb but not python object for lists of embedded documents
I've run into a issue with updating a list of embedded documents. There is an easy way around it for now, but I think it qualifies as a bug since it doesn't do what you'd expect as a python developer. The following code will provide an explanation better than I could with just English:
from mongoengine import Document, EmbeddedDocument, StringField, \
ListField, EmbeddedDocumentField, connect
import mongomock
# create a document that contains a list of embedded documents
class Book(EmbeddedDocument):
title = StringField(required=True)
class Library(Document):
shelf = ListField(EmbeddedDocumentField(Book))
# connect to test DB
connect(db="test", host="mongomock://localhost")
# create a book and a library with that book in it
book = Book(title="My Book")
library = Library()
library["shelf"].append(book)
library.save()
# Querying the DB, we see that the book saved correctly
print(Library.objects().first()["shelf"])
# Remove the book from the library
library.update(pull__shelf=book)
# Querying the DB again, we can see that the embedded Book document was removed
print(f"Library.objects().first()['shelf'] --> {Library.objects().first()['shelf']}")
# But list of embedded documents in the python object we just updated remains unchanged
print(f"library['shelf'] --> {library['shelf']}")
Obviously it's not hard as a programmer to just query the DB again to get the updated list of embedded documents, but that isn't expected behavior from a python object perspective. Additionally, it creates an extra call to the database when the data could be retrieved locally.