pythonmongoengine

How to update an item of embedded list field by index in Mongoengine?


I have a project using GraphQL and Mongoengine. To update a specific element of an embedded list field I do not want to get the whole list from the client instead I want to get a new value and the index along with the field name to update.

Here is a sample Post model



class Tag(EmbeddedDocument):
   value = StringField()
   description = StringField()

class Post(Document):
    content = StringField()
    tags = EmbbeddedDocumentListField(Tag)

class PostRepository:
    def get(self, **kwargs):
        return Post.object.filter(**kwargs).first()
    
    def update(self, query: dict, update_fields: dict):
        post = self.get(**query)
        post.modify(query=None, **update_fields)
        return post

Here is my resolver


def update_post_resolver(id: str):
    post_repository = PostRepository()
    return post_repository.update({"id": id}, {"set__tags__0": {"value": "Python", "description": "..."})

But it raises the following error

    raise ValueError(
ValueError: The source SON object needs to be of type 'dict' but a '<class 'str'>' was found


    raise InvalidQueryError(
mongoengine.errors.InvalidQueryError: Querying the embedded document Tag failed, due to an invalid query value

So, it possible to update a specific tag element by its index as an underscore keyword argument in Mongoengine?


Solution

  • I solved it. The value should be passed by the embedded document instead of dict.

    The following query is working .

    post_repository.update({"id": id}, {"set__tags__0": Tag(value="Python", description= "..."))