使用switch_collection
方法保存文档时,我的行为很奇怪。
可以使用以下代码复制:
switch_collection
[当调用import mongoengine as me
class ObjectA(me.Document):
name = me.StringField()
def test_strange_behaviour():
a_0 = ObjectA(name="a_0")
a_0.save()
a_1 = ObjectA(name="a_1")
a_1.save()
a_1.switch_collection("new_collection", keep_created=False)
a_1.id = a_0.id
a_1.save()
print(a_1._collection)
print(a_1._collection.find_one(a_1.id))
函数时,代码将显示如下内容:
test_strange_behaviour
您可以看到,最后的打印显示在Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary(), connecttimeoutms=30000, heartbeatfrequencyms=3000, ssl=False), 'engine'), 'new_collection')
{'_id': ObjectId('5dc57611dba04ca06410e477')}
集合上创建的文档仅包含new_collection
字段,而不包含_id
字段。如果name
为keep_created
,也会发生相同的情况。
为什么会这样?这个例子有问题吗?
将True
归于a_0.id
后,应将其保存为a_1.id
,否则就只是更新force_insert=True
。