在mongoengine中更新嵌入文档的列表字段的正确方法是什么? [英] What is the proper way to update a listfield of embedded documents in mongoengine?

查看:170
本文介绍了在mongoengine中更新嵌入文档的列表字段的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to define methods for performing checks and updates to a listfield of embedded documents in mongoengine. What is the proper way of doing 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 correct way to go about something like this?

推荐答案

您可以使用EmbeddedDocumentListField而不是嵌入式文档列表.这样,您就可以访问某些方便的方法,例如过滤器创建更新:

You could use an EmbeddedDocumentListField instead of a list of embedded documents. That way you get access to some handy methods like filter, create or update:

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)

(代码未经测试)

这篇关于在mongoengine中更新嵌入文档的列表字段的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆