4

I am working on a task where i am taking the id generated from the database collection and i passing it through the postman.. i am converting that it to database obejct id created and its working accordinlg if we pass correct id else it is throwing an error

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
        }
    }

when ever i am not passing the valid input it is throwing the following error

   <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>
2
  • You're passing an illegal value to new ObjectId and so an exception is thrown. What would you want to happen instead? Commented Mar 22, 2018 at 7:04
  • i am matcing with the id value in the database and it is working accordingly but in the negative test cases when ever enterinng the invalid id it should not fetch any records from the db but instead it is throwing an error .. but if we pass an id in the form of the same pattern even if is not present it is working fine Commented Mar 22, 2018 at 7:10

3 Answers 3

1

1-

If you're using mongoose, and you're trying to perform a search operation on the basis if _id you don't actually need to convert the passed id to objectId. just use

 mongo.get().collection("post")find({"_id" : req.headers.postid })

This won't impose the passed id to be a constructable to monogdb's objectId as objectId in mongo db follows special pattern. Like

12-byte structure, the first 4 bytes of the ObjectId represent the time in seconds since the UNIX epoch.

The next 3 bytes of the ObjectId represent the machine identifier.

The next 2 bytes of the ObjectId represent the process ID.

And the last 3 bytes of the ObjectId represent a random counter value.

And if your passed id is not constructable to the pattern mentioned above this is definitely gonna throw the errors like you're getting

2

Well I am not very sure about this approach but you can first check if id passed is OK or not with something like

var id = null;
try {
 id  =  new ObjectId(req.headers.postid)
  mongo.get().collection("post").find({"_id":id}).toArray(function(err, result) {
....

}
 catch(error) {
 console.error(error);
 //there must be error with the id
} 
Sign up to request clarification or add additional context in comments.

4 Comments

its not fetching the record if we use this
Oh Sorry. I didn't notice , you don't have mongoose tag in your question. This will work with mongoose. let me update
i found one more solution for this if we verify the id with isMongoId(str) in if codition and in else we can perform the remaining task ... its working for me .." isMongoId(str) is a validator npm module function "
Great. Have fun
1
if(!validator.isMongoId(req.headers.postid)){
 res.send("invalid post id ")
}
else{
 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
        }
    }
}

before that install validator npm module

Comments

0

If you are okay with monk, you can use this.
var Id = require('monk').id(req.headers.postid);

1 Comment

thanks for the reply ,i dont that but i will try if nothing works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.