【发布时间】:2018-08-31 12:27:39
【问题描述】:
我正在处理一项任务,我正在获取从数据库集合生成的 id,并将其传递给邮递员。如果我们传递正确的 id,我将其转换为创建的数据库对象 id 及其工作的accordinlg正在抛出错误
mongo.get().collection("post").find({"_id":new ObjectId(req.headers.postid)}).toArray(function(err, result) {
if (err) throw err;
if(result.length==0){
jsonObj.response="post id entered is invalid ";
res.send(jsonObj)
}
else{
//some operations
}
}
当我没有传递有效输入时,它会引发以下错误
<body>
<h1>Argument passed in must be a single String of 12 bytes or a string of 24 hex characters</h1>
<h2></h2>
<pre>Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/bson/lib/bson/objectid.js:51:11)
at Object.handle (/home/vamsi/nodejs-training/myfirstproject/facebook/routes/updatepost.js:36:47)
at next_layer (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/route.js:107:5)
at /home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:195:24
at Function.proto.process_params (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:251:12)
at next (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:189:19)
at Function.proto.handle (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:234:5)
at Layer.router (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:23:12)
at trim_prefix (/home/vamsi/nodejs-training/myfirstproject/facebook/node_modules/express/lib/router/index.js:226:17)</pre>
</body>
</html>
【问题讨论】:
-
您将非法值传递给
new ObjectId,因此引发异常。你希望发生什么? -
我与数据库中的 id 值匹配,它正在相应地工作,但是在负面测试用例中,当输入无效 id 时,它不应该从数据库中获取任何记录,而是抛出一个错误..但是如果我们以相同模式的形式传递一个 id 即使不存在它也可以正常工作
标签: javascript node.js mongodb mongodb-query postman