What is the proper way to update a listfield of embedded documents in mongoengine?

后端 未结 2 400
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 10:25

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

2条回答
  •  故里飘歌
    2021-02-06 11:05

    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)
    

    (code not tested)

提交回复
热议问题