[英]Mongoose update Many documents in DB with condition
嗨,我需要一些幫助來更新我的產品集合中的許多文檔,它必須與updateData.oldCategoryName
和updateData.userId
匹配,然后設置所有與updateData.newCategoryName
匹配並更新類別名稱的產品。
let products = [
{id: 1, name: 'Brasilian', category: 'cofee', userId: 9},
{id: 2, name: 'Colombian', category: 'cofee', userId: 9},
{id: 3, name: 'Apple', category: 'fruit', userId: 8},
{id: 4, name: 'Strawberry', category: 'fruit', userId: 8},
{id: 5, name: 'Banana', category: 'fruit', userId: 7}
];
let updateData = {
userId: 8,
oldCategoryName: 'fruit',
newCategoryName: 'good fruit'
};
如何設置條件並使用 mongoose 更新許多文檔? 提前致謝。
這是我用來更新單個產品的代碼段:
Product.findByIdAndUpdate(productId, updateData, {new: true}, (err, productUpdated) => {
if(err) return res.status(500).send({message: 'Error al actualizar'});
if(!productUpdated) return res.status(404).send({message: 'No existe el producto'});
return res.status(200).send({product: productUpdated});
});
使用貓鼬,您可以使用updateMany()
函數。
試試這個查詢:
Product.updateMany({
userId:req.body.userId
category: req.body.oldCategoryName
},
{
$set:{
category: req.body.newCategoryName
}
})
有了這個查詢你告訴那里蒙戈“更新所有元素userId
是必需的帳戶及category
進行所需的類別,然后將所有類別與新值匹配。
示例在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.