【问题标题】:Validation Error on nested Embedded Documents in MongoEngineMongoEngine中嵌套嵌入文档的验证错误
【发布时间】:2020-06-06 22:20:33
【问题描述】:

我正在创建具有两个级别的嵌套嵌入式文档(嵌入式文档内的嵌入式文档)

代码如下:

from mongoengine import *

class CommentDetails(EmbeddedDocument):
    name = StringField()
    category = StringField()

class Comment(EmbeddedDocument):
    content = StringField()
    comments = ListField(EmbeddedDocumentField(CommentDetails))

class Page(Document):
    comments = ListField(EmbeddedDocumentField(Comment))

comment1 = Comment(content='Good work!',comments=CommentDetails(name='John',category='fashion'))
comment2 = Comment(content='Nice article!',comments=CommentDetails(name='Mike',category='tech'))

page = Page(comments=[comment1, comment2])
page.save()

运行时出现以下错误:

ValidationError: ValidationError (Page:None) (cmets.Only 列表和元组可以在列表字段中使用>1.cmets.Only 列表和元组可以在列表字段中使用: ['cmets'])

我尝试使用单个嵌套文档并且它可以工作,如果我不使用 EmbeddedDocuments 列表它也可以工作。但不确定为什么它不适用于多层嵌入式文档列表。

【问题讨论】:

    标签: python mongodb mongoengine


    【解决方案1】:

    问题出在以下两行:

    comment1 = Comment(content='Good work!',comments=CommentDetails(name='John',category='fashion'))
    comment2 = Comment(content='Nice article!',comments=CommentDetails(name='Mike',category='tech'))
    

    comments 应该是一个列表,但你提供了一个对象。

    使用这个:

    comment1 = Comment(content='Good work!',comments=[CommentDetails(name='John',category='fashion')])
    comment2 = Comment(content='Nice article!',comments=[CommentDetails(name='Mike',category='tech')])
    

    【讨论】:

    • 哦!现在明白了。它应该是一个列表,因为它是一个列表字段。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    相关资源
    最近更新 更多