[英]Is there a way to update multiple documents with different values in mongoose?
I'm feeling like there probably isn't a way to do this, but here's what I want to accomplish, I have an array of products to update like so:我觉得可能没有办法做到这一点,但这是我想要完成的,我有一系列产品要更新,如下所示:
const productsToUpdate = [
{
"imgUrls": {
"base": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
],
"side": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
]
},
"_id": "5dd6173cf50c1d1a40fe7c2c",
"category": "MENS",
"name": "JavaScript is Cool",
"price": "27.50"
},
{
"imgUrls": {
"base": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
],
"side": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
]
},
"_id": "5dd6173cf50c1d1a40fe7c2c",
"category": "MENS",
"name": "Testing",
"price": "25.50"
}
]
This data structure matches the data of products currently stored in my database.此数据结构与当前存储在我的数据库中的产品数据相匹配。 Basically, I need to find a current product by _id and be able to update either the category, price, imgUrls, or name or all of the above.基本上,我需要通过 _id 查找当前产品,并且能够更新类别、价格、imgUrls 或名称或以上所有内容。
I've done some research and know I can grab all the ids from the toUpdate arr and then do something like我做了一些研究,知道我可以从 toUpdate arr 中获取所有 id,然后执行类似的操作
Collection.update({ _id: { $in: arrOfIds }, {}, {multi: true}))
But I'm not sure how to fill in the query to have the correct category/price/name etc.但我不确定如何填写查询以获得正确的类别/价格/名称等。
I would greatly appreciate any guidance or if you need more information please let me know!我将不胜感激任何指导,或者如果您需要更多信息,请告诉我!
The "mass-update" or rather the most efficient way of that kind of updates is called bulkWrite . “大规模更新”或更有效的这种更新方式称为bulkWrite 。 Since there are is more fields in your database and you don't want to lose them you need to use $set operator.由于您的数据库中有更多字段并且您不想丢失它们,因此您需要使用$set运算符。
const productsToUpdate = [
{
"imgUrls": {
"base": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
],
"side": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
]
},
"_id": "5dd6173cf50c1d1a40fe7c2c",
"category": "MENS",
"name": "JavaScript is Cool",
"price": "27.50"
},
{
"imgUrls": {
"base": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
],
"side": [
"https://files.cdn.printful.com/files/ba1/ba13faa1332b7f18ec847cb9f4d79868_preview.png"
]
},
"_id": "5dd6173cf50c1d1a40fe7c2c",
"category": "MENS",
"name": "Testing",
"price": "25.50"
}
];
let toUupdate = product => ({
updateOne: {
"filter": { "_id": product._id },
"update": { "$set": { category: product.category, name: product.name, price: product.price } }
}
})
db.collection.bulkWrite(productsToUpdate.map(toUupdate);
console.log(updates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.