In mongo, is it possible to have an _id that would look valid but could never exist?

I am making unit tests for a web application and I want to make a test case to see if my app will send back the appropriate error message when someone tries to get a mongo document that could never exist.

To give a bit more context, The web app sends back information about certain items based off the _id of that item in the mongo database. The user is able to get the _id of any item as all items are view-able to the public.

What I want to know is, is it possible to have an _id that could be queried in a database but it could never exist?

If this is possible then I could make a test case that would query the mongo db and send back the appropriate error message every time guaranteed. Right now, I'm using a mongo _id that was assigned to an item that no longer exists.

My requirement for this _id is that:

  • 1) it needs to be the same length of a normal _id
  • 2) it needs to be composed of the same characters as a _id (hexadecimal I'm assuming)
  • 3) it could never actually be a real _id that mongo would assign to a document.

Its also worth noting, that the user could never assign a _id when they create an item. All _id assignment is being handled by mongo.

If it fits all of the above I would be happy.

They only thing I could think of is 000000000000000000000000 but I cant confirm if this can be used as an _id or not?

1 answer

  • answered 2017-08-17 16:50 Sergio Tulentsev

    but, for some reason, mongo would never be able to assign that _id

    You need to distinguish "mongodb will never generate this id" and "mongodb will never accept this id if we provide it".

    For the former, your example of all-zero object id is fine. Mongodb will never generate an id like that (because of timestamp generation rule, if nothing else)

    If the latter, it's impossible. A mongo object id is basically a 12-byte binary blob, with no invalid or restricted values. All values are valid.

    Also note that _id field can take most any value: strings, numbers, object ids, objects, what-have-you. Except arrays.