reactjs - 我怎么知道 save 方法在 mongo 中是否有效
问题描述
我是使用 mongo 的新手,当我在我的数据库中保存一个新对象时,我使用 save 方法,但是当使用它然后打印结果时,如果它成功我得到了对象,而不是我可以用来处理任何错误的东西前端
router.post("/post_recipe", async (request, response) => {
const {title, content, author} = request.body;
const new_post = new Posts({title, content, author});
new_post.save(sdfs).then((response) => {
response.json(response);
}).catch(error => response.json(error));
});
故意这样做我在控制台中收到错误,但它没有将其发送到前端来处理它并告诉用户有问题
贴出一个方案,不知道有没有关系
解决方案
问题是您对路由器响应和保存方法响应使用相同的变量名。
解决方案
router.post("/post_recipe", async (req, res) => {
const {title, content, author} = req.body;
const new_post = new Posts({title, content, author});
// Getting rid of .then and .catch method
new_post.save((err, savedPost) => {
// Your custom error message
if (err) return res.status(400).json('post not saved due to some problem! Please try again');
// Post that you just saved in db
return res.json(savedPost);
});
这是由于变量的范围而发生的。
有关更多详细信息,请查看w3schools.com 的这篇文章