我一直在处理相同的错误,代码可以很好地用于记录的添加,获取和删除,但是当我尝试发送发布更新请求时,Postman上出现了错误。 邮差和失眠都普遍存在相同的错误。
const router = require("express").Router();
let Exercise = require("../models/exercise.model");
router.route("/").get((req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
const newExercise = new Exercise({
username,
description,
duration,
date
});
newExercise
.save()
.then(() =>
res
.json("Exercise added!")
.catch(err => res.status(400).json("Error: " + err))
);
});
router.route("/:id").get((req, res) => {
Exercise.findById(req.params.id)
.then(exercise => res.json(exercise))
.catch(err => res.status(400).json("Error: " + err));
});
router.route("/:id").delete((req, res) => {
Exercise.findByIdAndDelete(req.params.id)
.then(() => res.json("Exercise deleted."))
.catch(err => res.status(400).json("Error: " + err));
});
router.route("/update/:id").post((req, res) => {
Exercise.findById(req.params.id)
.then(exercise => {
exercise.username = req.body.username;
exercise.description = req.body.description;
exercise.duration = Number(req.body.duration);
exercise.date = Date.parse(req.body.date);
exercise
.save()
.then(() => res.json("Exercise Updated!"))
.catch(err => res.status(400).json("Error: " + err));
})
.catch(err => res.status(400).json("Error: " + err));
});
module.exports = router;
POST的正文为:
{
"username": "Omer Mustafa",
"description": "Walk",
"duration": "120",
"date": "2019-10-07T11:19:09.424Z"
}
我正在按照本教程进行实验,以构建一个简单的mern应用程序: https://www.youtube.com/watch?v=7CqJlxBYj-M
答案 0 :(得分:0)
mongoose FindById不会引发异常,但是会返回null。 因此,在使用之前,您需要检查数据是否不为null。 您只需要添加此检查:
if (!exercise) return res.status(404).send();
因此,所有与更新相关的代码现在看起来都是:
router.route("/update/:id").post((req, res) => {
Exercise.findById(req.params.id)
.then(exercise => {
if (!exercise) return res.status(404).send();
exercise.username = req.body.username;
exercise.description = req.body.description;
exercise.duration = Number(req.body.duration);
exercise.date = Date.parse(req.body.date);
exercise
.save()
.then(() => res.json("Exercise Updated!"))
.catch(err => res.status(400).json("Error: " + err));
})
.catch(err => res.status(400).json("Error: " + err));
});