kikiriki
kikiriki

Reputation: 1

Mongoengine: update only specified fields on embedded document

I have the following schema:

class Task(EmbeddedDocument):
    description = StringField()
    is_finished = BooleanField(default=False)

class Plan(DynamicDocument):
    priority = IntField()
    tasks = EmbeddedDocumentListField(Task)

Then I create a plan instance from dictionary (originally I'm getting the dictionary from json body of http request):

body = {"priority": 1, "tasks": [{"description": "do this", "is_finished": true}]}

plan = Plan(**body).save()

Then I'm trying to update description of the task embedded document while leaving its other field is_finished unchanged and also leaving priority field of plan unchanged:

new_body = {"tasks": [{"description": "do that"}]}
plan.update(**new_body)

However after the update is_finished value changes to false (it's default value).

print(plan.to_json())
# prints {"priority": 1, "tasks": [{"description": "do that", "is_finished": false}]}

How can I update document while keeping unspecified embedded fields unchanged just like I did with priority field on main document? I tried removing default value from embedded document model but then I just drops the field completely if it's not specified during update.

Upvotes: 0

Views: 449

Answers (1)

Krithika Ramakrishnan
Krithika Ramakrishnan

Reputation: 128

This will update the specific field

plan.update(set__tasks__0__description='your new description')

Here, 0 is the ordinality of the Embedded Document (in the list 'tasks') whose description you want to update.

Upvotes: 1

Related Questions