简体   繁体   English

使用 nodejs 和 mongodb 的 UnhandledPromiseRejection 问题

[英]UnhandledPromiseRejection problem with using nodejs and mongodb

The service I wrote with node js runs smoothly, I successfully created create, delete, put, read from postman.我用node js写的服务运行流畅,我成功创建了create,delete,put,read from postman。 When I press delete button on React interface, I get the error I shared below.当我在 React 界面上按下删除按钮时,我收到了我在下面分享的错误。 When I press the delete button, the deleteUser() method is triggered.当我按下删除按钮时,deleteUser() 方法被触发。 It gives an error related to id.它给出了与 id 相关的错误。 What should I change to resolve this error?我应该更改什么来解决此错误?

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)

model模型

const mongoose = require('mongoose')
const Schema = mongoose.Schema

newSchema = new Schema({
    name : String,
    email : String,
    password : String
})

module.exports = mongoose.model('User', newSchema)

routes路线

/* 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'})
})

react ui反应界面

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
            })
        })
}

package.json包.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"
  }
}

You haven't provided exact instructions how your id is passed around but the error you are getting is likely because the ObjectId is not a valid ObjectId.您尚未提供如何传递您的 id 的确切说明,但您收到的错误可能是因为 ObjectId 不是有效的 ObjectId。 A valid ObjectId is a 12 byte in length.一个有效的 ObjectId 是一个 12 字节的长度。

it probably comes from here tho:它可能来自这里:

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:''
          })
    })
}

If that is indeed the issue get into the practice of having MongoDB generate your Object Id instead of you setting it如果这确实是问题,请实践让 MongoDB 生成您的对象 ID 而不是您设置它

Look here for more information: ObjectId在这里查看更多信息: ObjectId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM