节点findById()仅在无效的ID上崩溃:对于值,转换为ObjectId失败

时间:2018-04-06 13:23:48

标签: javascript node.js mongodb mongoose

好的,我有一个基本的GET方法,用于根据MongoDB数据库中的ID返回“流派”并由Mongoose调用。 当id有效时,这很好用但是一旦它无效就会崩溃我的应用程序。

我的代码:

router.get('/:id', async (req, res) => {
    const genre = await Genre.findById(req.params.id);
    if(!genre) return genreNotFoundError(res);
    res.send(genre);
});

// Helper Functions

function genreNotFoundError(res) {
    res.status(404).send('Genre not found');
}

这是请求和正文:

http://localhost:5000/api/genres/5ac68d7d7d113ded8c36f3fc

{
    "_id": "5ac68d7d7d113ded8c36f3fc",
    "name": "Drama",
    "__v": 0
}

崩溃发生在_id字段更改的位置,如下所示:

http://localhost:5000/api/genres/1234

这给我以下错误。

我尝试过使用其他帖子中建议的findByOne({_id: req.params.id}),但似乎没有做任何事情。

错误:

(node:70853) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "1234" at path "_id" for model "Genre"
    at new CastError (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/error/cast.js:27:11)
    at ObjectId.cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schema/objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:724:12)
    at ObjectId.SchemaType._castForQuery (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:1095:15)
    at ObjectId.castForQuery (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schema/objectid.js:198:15)
    at ObjectId.SchemaType.castForQueryWrapper (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/schematype.js:1064:15)
    at cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/cast.js:300:32)
    at model.Query.Query.cast (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:3208:12)
    at model.Query.Query._castConditions (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:1280:10)
    at model.Query.Query._findOne (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/mongoose/lib/query.js:1496:8)
    at process.nextTick (/Users/richardcurteis/Development/Courses/NodeJsCourse/vidly-node/node_modules/kareem/index.js:311:33)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
(node:70853) 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(). (rejection id: 1)
(node:70853) [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 个答案:

答案 0 :(得分:1)

您应该为db调用添加适当的错误处理:

 router.get('/:id', async (req, res) => {
  try {
   const genre = await Genre.findById(req.params.id);
   if(!genre) return genreNotFoundError(res);
   res.send(genre);
  } catch(e) {
    return genreNotFoundError(res);
  }
});

答案 1 :(得分:1)

好吧,Jonas W总结了这一点。您可以使用validator

执行此操作

这样的东西
if(!validator.isMongoId(req.params.id)){
res.send("invalid id ")
} else ...//handle your request