I'm new to Mongoose. How do you update multiple at once? without repeating updateOne three times as what I have done? Thanks!
app.post("/editProduct",(req,res)=>{
const reqProduct = req.body.product;
const reqStock = req.body.stock;
const reqSupplier = req.body.supplier;
const reqProductId = req.body.productId;
Product.updateOne({_id:reqProductId},{product:reqProduct},(err)=>{
if(err){
console.log(err);
}else{
console.log("product updated successful");
}
});
Product.updateOne({_id:reqProductId},{stock:reqStock},(err)=>{
if(err){
console.log(err);
}else{
console.log("product updated successful");
}
});
Product.updateOne({_id:reqProductId},{supplier:reqSupplier},(err)=>{
if(err){
console.log(err);
}else{
console.log("product updated successful");
}
});
res.redirect('/products/' reqProductId);
});
CodePudding user response:
Try this solution:
app.post("/editProduct", (req, res) => {
const reqProduct = req.body.product;
const reqStock = req.body.stock;
const reqSupplier = req.body.supplier;
const reqProductId = req.body.productId;
Product.update({
_id: reqProductId
}, {
"$set": {
product: reqProduct,
stock: reqStock,
supplier: reqSupplier,
}
}, {
"multi": true
}, (err, writeResult) => {
if (err) {
console.log(err);
} else {
console.log("product updated successful");
}
});
res.redirect('/products/' reqProductId);
});