MongoEngine递归嵌入
MongoEngine recursive embedding
我正在尝试使用 mongoengine 为文档建模,但我不知道如何进行递归嵌入。例如我想做这样的事情
class NavigationHelper(EmbeddedDocument):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField(NavigationHelper)
我将使用它来创建具有无限子菜单可能性的导航树。例如
-菜单-1
--sub-menu-1-1
---子菜单-1-1-1
---子菜单-1-1-2
----sub-menu-1-1-2-1
-菜单-2
有什么方法可以模拟这个吗?非常感谢。
您可以使用一个高级别 Document
和 EmbeddedDocument
的列表来建模。
from mongoengine import Document, EmbeddedDocument, StringField, URLField, EmbeddedDocumentListField
# The embeddedDocument of sub-menus
class NavigationSubMenu(EmbeddedDocument):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField('NavigationSubMenu')
# The document for the main menus
class NavigationMenu(Document):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField(NavigationSubMenu)
您提供的示例将由以下人员创建:
docs = [
NavigationMenu(name='1',
sub_menus=[
NavigationSubMenu(name='1-1',
sub_menus=[
NavigationSubMenu(name='1-1-1'),
NavigationSubMenu(name='1-1-2',
sub_menus=[
NavigationSubMenu(name='1-1-2-1')
])
])
]
),
NavigationMenu(name='2')
]
for doc in docs:
doc.save()
docs = NavigationMenu.objects()
for doc in docs:
print(doc.name)
while len(doc.sub_menus) > 0:
for sub_menu in doc.sub_menus:
print(sub_menu.name)
doc = sub_menu
>> 1
>> 1-1
>> 1-1-1
>> 1-1-2
>> 1-1-2-1
>> 2
如果保存此文件,您将获得 2 个文档。每个高级别一个 NavigationMenu
.
我正在尝试使用 mongoengine 为文档建模,但我不知道如何进行递归嵌入。例如我想做这样的事情
class NavigationHelper(EmbeddedDocument):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField(NavigationHelper)
我将使用它来创建具有无限子菜单可能性的导航树。例如
-菜单-1
--sub-menu-1-1
---子菜单-1-1-1
---子菜单-1-1-2
----sub-menu-1-1-2-1
-菜单-2
有什么方法可以模拟这个吗?非常感谢。
您可以使用一个高级别 Document
和 EmbeddedDocument
的列表来建模。
from mongoengine import Document, EmbeddedDocument, StringField, URLField, EmbeddedDocumentListField
# The embeddedDocument of sub-menus
class NavigationSubMenu(EmbeddedDocument):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField('NavigationSubMenu')
# The document for the main menus
class NavigationMenu(Document):
name = StringField()
url = URLField()
sub_menus = EmbeddedDocumentListField(NavigationSubMenu)
您提供的示例将由以下人员创建:
docs = [
NavigationMenu(name='1',
sub_menus=[
NavigationSubMenu(name='1-1',
sub_menus=[
NavigationSubMenu(name='1-1-1'),
NavigationSubMenu(name='1-1-2',
sub_menus=[
NavigationSubMenu(name='1-1-2-1')
])
])
]
),
NavigationMenu(name='2')
]
for doc in docs:
doc.save()
docs = NavigationMenu.objects()
for doc in docs:
print(doc.name)
while len(doc.sub_menus) > 0:
for sub_menu in doc.sub_menus:
print(sub_menu.name)
doc = sub_menu
>> 1
>> 1-1
>> 1-1-1
>> 1-1-2
>> 1-1-2-1
>> 2
如果保存此文件,您将获得 2 个文档。每个高级别一个 NavigationMenu
.