node.js - 尝试更新或删除帖子时出错
问题描述
我编写了一个代码,用于在 MongoDB 中发布和更新数据,用于删除数据,当我想在 mongoDB 中更新某些内容时,它会毫无问题地发布,但成功后我不能redirect
。
主要问题是更新部分,因为这根本不起作用,我只得到错误:
我findByIdAndUpdate()
在路线中使用,这是发布项目部分和更新项目的代码:
发布项目(路由器部分):
router.post( "/", async( req, res, next ) => {
log.info(
`Adding new car category - `,
req.body,
req.headers
)
try {
let { title, author, description } = req.body;
let avto = new Avto({
title,
author,
description
})
await avto.save()
return res.send( { success: true } )
} catch ( ex ) {
log.error(
`Error`,
ex
)
return next( {
msg: "Error while trying to save car category.",
code: "CAR_SAVE_ERROR",
status: 403
} )
}
})
发布项目(/src/pages 部分):
addCar = async() => {
try {
let addCar = await axios.post( 'http://127.0.0.1:8080/avto', {
title: this.state.title,
description: this.state.description,
author: this.state.author
})
if ( addCar.data.success ) {
console.log( "Car successfully added!" );
}
} catch ( err ) {
console.log( err )
}
}
更新项目(路由器部分):
router.put('/update/:id', async (req, res, next) => {
log.info(`Updating car `,
req.body,
req.headers)
try {
Avto.findByIdAndUpdate(req.params.id,{$set:req.body}, {upsert:true}, function(err, avto){
return res.send("Succesfully Updated!");
})
} catch ( err ) {
return next( {
msg: "Error while trying update car.",
code: "CAR_UPDATE_ERROR",
status: 403
})
}
} )
更新项目(/src/pages 部分):
updateCar = async() => {
try {
let carId = this.props.match.params.id
let updateCar = await axios.get( `http://127.0.0.1:8080/update/${carId}`, {
id: this.state.id,
title: this.state.title,
description: this.state.description,
author: this.state.author
})
if ( updateCar.data.success ) {
console.log( "Car successfully updated!" );
}
} catch ( err ) {
console.log( err )
}
}
我究竟做错了什么?我是 JS 的初学者。
解决方案
我认为保存部分有问题。它应该是这样的:
router.post( "/avto", async( req, res, next ) => {
log.info(
'Adding new car category - ',
req.body,
req.headers
);
推荐阅读
- reactjs - 状态未从 NaN 更新
- firebase - GAE python项目中Firebase身份验证的完整示例?
- python-2.7 - xgboost 模型 getfscore:'str' 对象不可调用
- ruby-on-rails - 在 f.select onchange 函数中传递一个 ruby 变量
- amazon-web-services - 限制 S3 存储桶更改为公开?
- android - okhttp3.Cache 不能在没有 @Inject 构造函数或 @Provides-annotated 方法的情况下提供
- python - 在外部硬盘上运行 python 脚本(训练神经网络)
- java - 检查 Firestore 集合中是否存在文档
- javascript - 如何使用正则表达式在angularjs中允许字母数字和某些特殊字符
- google-analytics - 从具有重复字段的 Bigquery 读取的数据流