我正在尝试在mongoengine中执行upsert函数。也就是说,如果文档存在,我想用新值更新它,如果它不存在,我想创建和插入。
我有对象列表。这些对象可以有也可以没有ObjectIds。例如:
[
{
"id" : ObjectId("5c1791b7397df4a9c8518342"),
"type": "Line"
},
{
"type": "Line"
}
]
如您所见,第二个对象没有Id。
我把我的查询写成:
updates = Collection.objects(
id=obj.get('id', None)).modify(
new=True,
upsert= True,
**update_dict
)
当我遍历列表时,obj
是每个对象。
注意:update_dict
是另一个dict,它从一个返回要设置的属性的函数中获取其值。 (例如:set__type:“Line”)
问题
第一个对象被修改得很好。但是有一个错误:
“'无'不是有效的ObjectId,它必须是12字节输入或24字符十六进制字符串”
显然,这是因为obj.get('id', None)
部分。
那么,有没有一种方法可以生成一个id,如果它作为None传递?
我用mongoose和nodejs尝试了同样的事情,如果我使用如下,它对我有用:
这是我的数组对象:
var arr = [
{
_id: "5c13de7d47zfe91e3484362f",
email: '[email protected]',
},
{
_id: "5c13de7d47zfe91e3484362f",
email: '[email protected]',
},
{
// _id: "5c66aa87751fz5368759f9bc", // Commented
email: '[email protected]',
}
]
现在我正在使用nodejs迭代数组,如下所示。
arr.forEach(async element => {
await Driver.findOneAndUpdate(
{
_id: Types.ObjectId(element._id)
},
{
email: element.email
},{ upsert: true, new: true }
).lean().exec();
});
它对我有用。它在前两种情况下更新文档并为最后一种情况插入新文档。主要是使用Types.ObjectId
,它用于指定ObjectId的类型。如果我这样做而没有指定Schema.Types.ObjectId
然后它不起作用。