我试图在NodeJS中更新MongoDB中的几个对象。 下面是我遇到的问题:
我有一个对象数组,看起来像这样:
[{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2200 TL"
},
{
"_id": "40", // this object is recently added so it doesn't
// have an oid it needs to be inserted instead of updating.
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "4+1 Ev Taşıma",
"value": "7000 TL"
},
]
我试图使用Collection.UpdateMany
更新这些对象中的每一个,并使用Upsert:true
来更新这些对象。下面是我编写的代码:
mongodb.collection('prices').updateMany({}, {$set: post.prices}, {upsert: true}, (error, result) => {
if(error) throw error;
res.json(response);
})
错误如下:
MongoError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not
{$set: [ { _id: "5ed611265828aa77c978afb4", advert_id: "5ec2e4a8bda562e21b8c5052", isCategory: false, name: "2+1
Ev Taşıma", value: "2000 TL", isVisible: false } ]}
问题似乎是我试图将prices数组直接传递到$set管道中。 什么是字段类型,如何将数组转换为字段类型。
非常感谢您的帮助,我很难在文档中找到相关的章节。 如果你也能在你的回答中链接文档的相关部分,我会非常感激的。
数据库文档:
{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2000 TL",
"isVisible": false
}
我在{$set:post.prices}
中看到问题
它应该是{$set:{'prices':post.prices}}
-您应该向$set
提供一个文档
参考