简体   繁体   English

无法更新mongo数据库

[英]Cannot update mongo database

i am trying decrease quantity value when button is clicked and sent it to database.i got product object as props.我正在尝试在单击按钮并将其发送到数据库时减少数量值。我得到了product object 作为道具。 i destructure quantity value and set quantity value as usestate initialize value我解构数量值并将数量值设置为使用状态初始化值

 const { description, img, name, supplier, quantity, price } = product
 const [updateQuantity, setUpdateQuantity] = useState(quantity)
 useEffect(() => {
    setUpdateQuantity(quantity)
 }, [quantity])

then i created a function handleDecrease function and linked it with button.heres my function然后我创建了一个 function handleDecrease function 并将其与按钮链接。这是我的 function

  const handleDecrease = () => {
    console.log(updateQuantity);
    setUpdateQuantity(updateQuantity - 1)
    fetch(`http://localhost:4000/product/${id}`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ updateQuantity: updateQuantity }),
    })
        .then((res) => res.json())
        .then((data) => console.log(data));
}

its working fine.when i click button quantity value is decreasing and mongo database is updating.but when i fresh this page i got updateQuantity value undefined and quantity object value null它工作正常。当我单击按钮时,数量值正在减少并且 mongo 数据库正在更新。但是当我刷新此页面时,我得到了updateQuantity值未定义和quantity object 值 null

my index.js code of express app我的 express 应用程序的 index.js 代码

 app.put('/product/:id', async (req, res) => {
  const id = req.params.id
  const data = req.body
  console.log(data);
  console.log(id);
  const filter = { _id: ObjectId(id) }
  const options = { upsert: true };
  
  const updateDoc = {
    $set: {
      updateQuantity: data.updateQuantity,
      
    },
  };

  const result = await productCollection.updateOne(filter, updateDoc, options);
  res.send(result)

})

.what did i do wrong? 。我做错什么了? why i am getting null为什么我收到 null

Try to change your updateDoc condition:尝试更改您的updateDoc条件:

app.put('/product/:id', async (req, res) => {
  const id = req.params.id;
  const data = req.body;
  const filter = { _id: ObjectId(id) };
  const options = { upsert: true };
  const updateDoc = { updateQuantity: data.updateQuantity };

  const result = await productCollection.updateOne(filter, updateDoc, options);

  res.send(result);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM