[英]Cannot update mongo database
我正在嘗試在單擊按鈕並將其發送到數據庫時減少數量值。我得到了product
object 作為道具。 我解構數量值並將數量值設置為使用狀態初始化值
const { description, img, name, supplier, quantity, price } = product
const [updateQuantity, setUpdateQuantity] = useState(quantity)
useEffect(() => {
setUpdateQuantity(quantity)
}, [quantity])
然后我創建了一個 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));
}
它工作正常。當我單擊按鈕時,數量值正在減少並且 mongo 數據庫正在更新。但是當我刷新此頁面時,我得到了updateQuantity
值未定義和quantity
object 值 null
我的 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)
})
。我做錯什么了? 為什么我收到 null
嘗試更改您的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.