0

I want to create a mongoID using an URI fragment as source. However, unless the URI really contains a properly formatted mongoId, I get the below error thrown.

What should I change to allow _id creation without throwing errors as wrapping it in a try/catch block doesn't do it?

Error:

500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format

The code:

var _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);

this.db.users.findById(_id, function(err, doc) {
    if (!err && !!doc) { res.send(JSON.stringify(doc)); } else {res.send(JSON.stringify({error: "Not found"));}
});

I use the mongoskin driver.

2
  • I'm pretty sure I understand what you're trying to, but can you show a sample URI? Commented Feb 21, 2012 at 17:24
  • /users/nonvalidid - throws error. /users/47cc67093475061e3d95369d - valid. Commented Feb 21, 2012 at 17:26

1 Answer 1

2

The error is being thrown on this line:

var _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);

If you wrap that in try/catch block it should work.

var _id = null
try {
  _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);
} catch (err) {
  res.send(JSON.stringify({error: "Not found"}));
  return;
}

this.db.users.findById(_id, function(err, doc) {
  if (!err) { 
    res.send(JSON.stringify(doc)); 
  } else {
    res.send(JSON.stringify({error: err.message}));
  }
});

Does this work for you?

Sign up to request clarification or add additional context in comments.

Comments

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.