在mongoengine中更新嵌入文档列表字段的正确方法是什么?

sas*_*ker 6 python mongoengine

我正在尝试定义对mongoengine中嵌入文档的列表字段执行检查和更新的方法.做我正在做的事情的正确方法是什么.代码如下.

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?
Run Code Online (Sandbox Code Playgroud)

这甚至是正确的方式去做这样的事情?

Ros*_*oss 1

您需要找到现有评论的索引。

然后,您可以用新注释覆盖旧注释(其中i是索引),例如:

post.comments[i] = new_comment
Run Code Online (Sandbox Code Playgroud)

然后只需执行 a post.save(),mongoengine 就会将其转换为$set操作。

或者,您可以只写$set例如:

Post.objects(pk=post.pk).update(set__comments__i=comment)
Run Code Online (Sandbox Code Playgroud)