当前位置:网站首页>UnhandledPromiseRejectionwarning:CastError: Cast to ObjectId failed for value

UnhandledPromiseRejectionwarning:CastError: Cast to ObjectId failed for value

2022-04-23 20:30:00 Different 213

UnhandledPromiseRejectionwarning:CastError: { One of the solutions }

  • Cause of error : I want to query the corresponding in the database id, Delete data . But the result is an error .

The error message is :UnhandledPromiseRejectionwarning:CastError: Cast to ObjectId failed for value " 5ffbb96755245c37047691fa" at path “_id” for model "User

  • My mistake is req.query.id The output is the same as what I entered manually id Have the same value , But use findOne() The method is to query the corresponding data in the database . Then take a closer look at the terminal display , The discovery may be due to spaces .

  • because req.query.id There is an error caused by blank space in the print result of .

As shown below, the terminal displays spaces :

image-20210111193709566

The following code is used to test and draw a conclusion :

if (req.query.id.trim() === '5ffbb8e355245c37047691f4') {
    
    console.log(' Results the same  ')
} else {
    
    console.log(req.query.id)
}

trim() Method , Remove the spaces on both sides of the string . The output result is :” Results the same “.

版权声明
本文为[Different 213]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210550451013.html