mongodb使用find()指定id查询报错,ObjectId失败问题
1.首先报错如下:UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "“604b59d1dd9be83f3c0d3f77"” at path “_id” for model “User”at model.Query.exec (F:\前端练习2\黑马vue\article-blog\node
1.首先报错如下:
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "“604b59d1dd9be83f3c0d3f77"” at path “_id” for model “User”
at model.Query.exec (F:\前端练习2\黑马vue\article-blog\node_modules_mongoose@5.11.15@mongoose\lib\query.js:4358:21)
at model.Query.Query.then (F:\前端练习2\黑马vue\article-blog\node_modules_mongoose@5.11.15@mongoose\lib\query.js:4452:15)
(Use node --trace-warnings ...
to show where the warning was created)
(node:14716) 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: 1)
(node:14716) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
2, 可以看出是id”处的值“604b59d1dd9be83f3c0d3f77”强制转换为ObjectId失败
为什么说强制转换为ObjectId失败,查了下数据库才知道
原来mongodb的id主键存储的是一个ObjectId
3.因此只要在模板代码中在传递参数前将id变量前把object类型转换成string类型
就解决报错了
更多推荐
所有评论(0)