What is the correct way to update the list of fields of embedded documents in mongoengine?

I am trying to define methods for performing checks and updates in the list box of embedded documents in mongoengine. What is the right way to do what I'm trying to do. The code is below.

class Comment(EmbeddedDocument): created = DateTimeField() text = StringField() class Post(Document): comments = ListField(EmbeddedDocumentField(Comment)) def check_comment(self, comment): for existing_comment in self.comments: if comment.created == existing_comment.created and comment.text == existing_comment.text: return True return False def add_or_replace_comment(self, comment): for existing_comment in self.comments: if comment.created == existing_comment.created: # how do I replace? # how do I add? 

Is this even the right way to do something like this?

+7
source share
2 answers

You can use EmbeddedDocumentListField instead of a list of embedded documents. Thus, you get access to some convenient methods , such as filtering, creating or updating:

 class Comment(EmbeddedDocument): created = DateTimeField() text = StringField() class Post(Document): comments = EmbeddedDocumentListField(Comment) ... def add_or_replace_comment(self, comment): existing = self.comments.filter(created=comment.created) if existing.count() == 0: self.comments.create(comment) else: existing.update(comment) 

(code not verified)

+2
source

You need to find the index of an existing comment.

Then you can overwrite the old comment with a new comment (where i is the index), for example:

 post.comments[i] = new_comment 

then just do post.save() and mongoengine will convert this to the $set operation.

Alternatively, you can simply write $set for example:

 Post.objects(pk=post.pk).update(set__comments__i=comment) 
+1
source

All Articles