我正在尝试使用最新版本的 mongoose 插入对象数组,或者更新相应的产品 ID 是否已存在。我一生都无法找出正确的使用方法(bulkWrite、updateMany 等),而且我似乎无法在不出现错误的情况下找出语法。例如,我正在尝试
Product.update({}, products, { upsert : true, multi : true }, (err, docs) => console.log(docs))
这会引发错误DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. MongoError: '$set' is empty. You must specify a field like so: {$set: {<field>: ...}
使用 updateMany 只会给我 $set 错误。我似乎找不到任何使用此方法的人的示例,只是想知道是否有人可以为我提供如何正确使用此方法的示例。
需要明确的是,我生成一个对象数组,然后我想将它们插入到我的数据库中,或者更新条目(如果它已经存在)。我想要匹配的字段称为pid
。任何提示或建议将不胜感激!
EDIT:
我的产品架构
const productSchema = new mongoose.Schema({
title : String,
image : String,
price_was : Number,
price_current : {
dollars : String,
cents : String
},
price_save_percent : String,
price_save_dollars : String,
price_save_endtime : String,
retailer : String
})
const Product = mongoose.model('Product', productSchema)
的一个例子products
正在传递的数组
[
{
title: 'SOME PRODUCT',
image: '',
price_was: '139.99',
price_current: { dollars: '123', cents: '.49' },
price_save_percent: '12%',
price_save_dollars: '16.50',
price_save_endtime: null,
pid: 'VB78237321',
url: ''
},
{ ... },
{ ... }
]