猫鼬,如何一次更新多个?

Mongoose, how to update multiple at once?

我是 Mongoose 的新手。你如何一次更新多个?没有像我所做的那样重复 updateOne 三遍?谢谢!

   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);
});

试试这个解决方案:

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);
});