当我使用MongoEngine向文档中添加嵌入式文档时,它会在列表为空时第一次运行但随后尝试说失败:mongoengine.errors.OperationError:无法保存文档(无法更新'sensorlist.1 .alert_list.0._cls'和'sensorlist.1.alert_list'同时)
以下测试代码演示了此问题:如果您运行它,您将在foo中看到一个新的集合/文档,其中包含带有qty 2嵌入式警报的S2嵌入式传感器。如果你再次运行它会爆炸 - 任何想法? Thx Bill
import mongoengine as ME
ME.connect('foo')
class Sensor(ME.EmbeddedDocument):
name = ME.StringField()
alert_list = ME.ListField()
class Alert(ME.EmbeddedDocument):
name = ME.StringField(default = 'new alert')
class SiteConfig(ME.Document):
siteid = ME.StringField()
sensorlist = ME.ListField(ME.EmbeddedDocumentField(Sensor))
if not SiteConfig.objects(siteid = '123456'):
newsite = SiteConfig(siteid = '123456')
newsite.save()
print("saved new site")
site = SiteConfig.objects(siteid = '123456').first()
newsensor = Sensor(name='S1')
site.sensorlist.append(newsensor)
site.save()
print("added sensor S1")
newsensor = Sensor(name='S2')
site.sensorlist.append(newsensor)
site.save()
print("added sensor S2")
for sensor in site.sensorlist:
if sensor.name =='S2':
alert = Alert()
sensor.alert_list.append(alert)
site.save()
print('added first alert to S2')
for sensor in site.sensorlist:
if sensor.name =='S2':
alert = Alert()
sensor.alert_list.append(alert)
site.save()
print('added second alert to S1')
答案 0 :(得分:0)
我通过复制MongoAlchemy中非常相似的代码解决了这个问题。这也失败了,但实际上给了我有用的异常信息,指出我的问题是我的Sensor类Alert_list定义需要指定它包含的类。 所以修复就像这样定义传感器:
class Sensor(ME.DynamicEmbeddedDocument):
name = ME.StringField()
alert_list = ME.ListField(ME.EmbeddedDocumentField(Alert))
在对这么小的问题感到痛苦之后,我可能会坚持使用MongoAlchemy!