Reactjs 当我更新MERN堆栈中的记录时,它会删除该对象
当我尝试更新记录时,它会删除对象而不是更新它们。我知道我的路线是正确的,因为它在邮递员那里工作 路线:Reactjs 当我更新MERN堆栈中的记录时,它会删除该对象,reactjs,express,routes,request,Reactjs,Express,Routes,Request,当我尝试更新记录时,它会删除对象而不是更新它们。我知道我的路线是正确的,因为它在邮递员那里工作 路线: router.route('/update/:id').post(function (req, res) { Bet.findById({ _id: req.params.id }, function (err, bets) { if (!bets) res.status(404).send("Data not found."); else {
router.route('/update/:id').post(function (req, res) {
Bet.findById({ _id: req.params.id }, function (err, bets) {
if (!bets)
res.status(404).send("Data not found.");
else {
bets.result = req.body.result;
bets.profit = req.body.profit;
bets.save().then(bets => {
res.json('Update complete.');
})
.catch(err => {
res.status(400).send("Unable to update.");
});
}
});
});
App.js
handleSelection = async (value, id, event, key) => {
const obj = {
result: "Win",
profit: profits,
}
axios.post("http://localhost:5000/bet/update/" + key.id, obj)
.then(res => console.log(res.data));
}
json的示例
{
"_id": "5ddfe84f07a48861b4c0c153",
"name": "asd",
"profit": "-10",
"result": "Loss"
}
当我的代码运行时,它会变成这样:
{
"_id": "5ddfe84f07a48861b4c0c153",
"name": "asd"
}
router.route('/update/:id').post(async (req, res) => {
console.log("req.body: ", req.body);
try {
const { result, profit } = req.body;
const response = await Bet.findByIdAndUpdate(req.params.id, {result,profit}, { new: true });
if (!response) return res.status(400).send("Data not found");
res.json("Update complete");
} catch (err) {
res.status(500).send("Something went wrong");
}
})
实际上,它不是删除文档,而是用空值覆盖现有字段。原因很可能是您没有在POST请求正文中发送结果和利润值 因此,我建议您在路由内console.log req.body以查看结果和值是否存在: 顺便说一句,您可以使用findByIdAndUpdate方法缩短代码,如下所示:
{
"_id": "5ddfe84f07a48861b4c0c153",
"name": "asd"
}
router.route('/update/:id').post(async (req, res) => {
console.log("req.body: ", req.body);
try {
const { result, profit } = req.body;
const response = await Bet.findByIdAndUpdate(req.params.id, {result,profit}, { new: true });
if (!response) return res.status(400).send("Data not found");
res.json("Update complete");
} catch (err) {
res.status(500).send("Something went wrong");
}
})
要发送POST请求,您可以使用postman和以下正文:
在您的node console.log中将记录以下内容:
在您看到它与postman一起工作后,您可以将内容类型标题添加到axios.post中,并尝试是否工作。还要确保console.log(“obj:,obj)
使用所需的数据记录对象
console.log("obj: ", obj);
axios.post("http://localhost:5000/bet/update/" + key.id, obj,
{
headers: { "content-type": "application/json" }
})
如何记录请求主体的控制台日志?放置控制台日志(请求主体);没有给我输出意味着你没有正确地发布请求正文。你能试着用邮递员发帖吗?@LukeRemming我在我的答案中添加了console.log,使用这个代码你能用邮递员向这个路由发送发帖请求并检查节点应用程序控制台中记录的内容吗?返回req.body:{},所以它是空的。那么我将如何通过结果和利润来表达呢?他们一定要处于这种状态吗?@LukeRemming我更新了答案,向邮递员发送了一个发帖请求。请先和邮递员一起测试,如果有效,就意味着问题出在你身上。