我有一个看起来像这样的数据结构:
addresses: [
{
type: 'home',
street: 'street',
city: 'city',
zipcode: 'zpipcode',
},
{
type: 'work',
street: 'street',
city: 'city',
zipcode: 'zpipcode',
}
]
我想这样建模
addresses: {
home: {
street: 'street',
city: 'city',
zipcode: 'zpipcode',
},
work: {
street: 'street',
city: 'city',
zipcode: 'zpipcode',
}
}
我现在正在使用GenericEmbeddedDocumentField,但到目前为止还没有运气。
答案 0 :(得分:0)
我找到了解决方案。看下面的代码。记住要导入示例中提到的mongoengine
类(Document,MapField等。)
模型定义示例
class Address(EmbeddedDocument):
street = StringField(required=True, max_length=256)
zipcode = StringField(required=True, max_length=16)
city = StringField(required=True, max_length=32)
country = StringField(default="Poland")
class User(Document):
email = EmailField(required=True)
addresses = MapField(field=EmbeddedDocumentField(Address))
用法示例
user = User(email='test@mail.com')
user.addresses['home'] = Address(street='street', zipcode='zip', city='city')
user.save()