[英]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.