mongodb使用find()指定id查询报错,ObjectId失败问题
发布日期:2022-02-06 00:27:11 浏览次数:23 分类:技术文章

本文共 1242 字,大约阅读时间需要 4 分钟。

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类型

在这里插入图片描述
就解决报错了

转载地址:https://blog.csdn.net/weixin_46182770/article/details/114852721 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:github打不开
下一篇:git简单使用(first)

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月03日 15时15分00秒