javascript - 使用nodejs和mongodb的UnhandledPromiseRejection问题
问题描述
我用node js写的服务运行流畅,我成功创建了create,delete,put,read from postman。当我在 React 界面上按下删除按钮时,我得到了我在下面分享的错误。当我按下删除按钮时,将触发 deleteUser() 方法。它给出了一个与 id 相关的错误。我应该改变什么来解决这个错误?
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:16381) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "${id}" at path "_id" for model "User"
at new CastError (/home/mutlueren/Desktop/mern-demo-app/backend/node_modules/mongoose/lib/error/cast.js:29:11)
at model.Query.exec (/home/mutlueren/Desktop/mern-demo-app/backend/node_modules/mongoose/lib/query.js:4331:21)
at model.Query.Query.then (/home/mutlueren/Desktop/mern-demo-app/backend/node_modules/mongoose/lib/query.js:4423:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16381) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
模型
const mongoose = require('mongoose')
const Schema = mongoose.Schema
newSchema = new Schema({
name : String,
email : String,
password : String
})
module.exports = mongoose.model('User', newSchema)
路线
/* find user by id */
router.get('/:id',(req, res) =>{
User.findById(req.params.id, (err, data) =>{
res.json(data)
})
})
/* delete user by id */
router.delete('/:id', async (req, res) =>{
await User.findByIdAndDelete(req.params.id)
res.json({'message':'deleted'})
})
/* create */
router.post('/',(req,res)=>{
user = new User({
name:req.body.name,
email:req.body.email,
password:req.body.password
})
user.save(()=>{
res.json(user)
})
})
/* update */
router.put('/:id', async (req, res)=>{
await User.findByIdAndUpdate(req.params.is, req.body)
res.json({'message':'updated'})
})
反应用户界面
constructor(props) {
super(props);
this.state = {
users : [],
id:0,
name:'',
email:'',
password:''
}
}
componentDidMount() {
axios.get('http://localhost:8080/api')
.then((res)=>{
this.setState({
users:res.data,
id:0,
name:'',
email:'',
password:''
})
})
}
nameChange = event =>{
this.setState({
name:event.target.value
})
}
emailChange = event =>{
this.setState({
email:event.target.value
})
}
passwordChange = event =>{
this.setState({
password:event.target.value
})
}
submit(event, id) {
event.preventDefault()
if(id === 0) {
axios.post('http://localhost:8080/api', {
name: this.state.name,
email: this.state.email,
password: this.state.password
})
this.componentDidMount()
}else{
axios.put('http://localhost:8080/api/${id}', {
name: this.state.name,
email: this.state.email,
password: this.state.password
})
this.componentDidMount()
}
}
deleteUser(id){
axios.delete('http://localhost:8080/api/${id}')
.then(()=>{
this.componentDidMount()
})
}
editUser(id){
axios.get('http://localhost:8080/api/${id}')
.then((res)=>{
this.setState({
name:res.data.name,
email:res.data.email,
password:res.data.password
})
})
}
包.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "nodemon ./index.js",
"start": "node index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"mongoose": "^5.9.7"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
解决方案
您尚未提供如何传递您的 id 的确切说明,但您收到的错误很可能是因为 ObjectId 不是有效的 ObjectId。有效的 ObjectId 长度为 12 个字节。
它可能来自这里:
componentDidMount() {
axios.get('http://localhost:8080/api')
.then((res)=>{
this.setState({
users:res.data,
id:0, <- You've set this to zero.
name:'',
email:'',
password:''
})
})
}
如果这确实是问题,请进入让 MongoDB 生成对象 ID 而不是设置它的实践
在这里查看更多信息:ObjectId
推荐阅读
- java - 如何在不使用 if 语句的情况下生成伪随机、唯一、排序整数数组?
- python - 如何使用 openCV 在两个相机之间转换坐标?
- reactjs - ERROR 错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:数字
- git - 如何使用主题分支和审阅者在本地推送 gerrit 分支中的提交
- javascript - 如何使用 javascript 将文本转换为链接版本?
- xamarin.forms - 如何将数据临时存储在应用程序内存中,以便在 Xamarin.Forms 中重新启动应用程序时不会保存数据?
- python - 直到使用 while 循环输入有效的循环。我需要一段时间,但在哪里?
- javascript - jquery - 页面加载时的活动选项卡
- cocoa - -[NSWindowController loadWindow] 中的编程窗口创建不起作用
- html - CSS Grid: 3x3 网格来填充父级的剩余空间