Sha*_*son 6 mongoose mongodb node.js mongodb-query
我正在尝试使用最新版本的 mongoose 插入一组对象,或者如果相应的产品 ID 已经存在则更新。我一生都无法找出正确的使用方法(bulkWrite、updateMany 等),而且我似乎无法在不出错的情况下弄清楚语法。例如,我正在尝试
Product.update({}, products, { upsert : true, multi : true }, (err, docs) => console.log(docs))
Run Code Online (Sandbox Code Playgroud)
这会引发错误 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. 任何提示或建议将不胜感激!
编辑:
我的产品架构
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)
Run Code Online (Sandbox Code Playgroud)
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: ''
},
{ ... },
{ ... }
]
Run Code Online (Sandbox Code Playgroud)
Ash*_*shh 13
你基本上需要bulkWrite操作
您要更新的数组
const 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: ''
}
]
Run Code Online (Sandbox Code Playgroud)
批量更新查询
Model.bulkWrite(
products.map((product) =>
({
updateOne: {
filter: { retailer : product.pid },
update: { $set: product },
upsert: true
}
})
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3964 次 |
| 最近记录: |