javascriptnode.jstypescriptmongodbmongoose

Is it possible to make a mongoDb objectId greater than 24 characters?


Just a simple question I could'nt get the answer through the doc nor stackoverflow:

I'd like to encode a discriminating unique value for my documents in the object id. That way, the unique value can be computed or retrieved when parsing the object id.

The main advantage for me are:

  • it's deterministic, so I can use it to seed my DB and create _ids before creating documents, or for using an upsert function
  • more efficient while getting by the unique value since searching by _id is more efficient than searching by the unique field (unless you create a new index I guess)

Here is the function I am using to do such an job:

export function convertNameToObjectId(ressourceName) {
  const slug = ressourceName.replace(/[^A-Za-z0-9_]/g, '')
  return Buffer.from(slug).toString('hex').padStart(24, '0')//.substring(0, 24) may not be needed
}

So 90% of the time this works great because the said unique value is less than 24 characters when convertes to hex string, but sometimes it's a bit larger and mongoose throw an error: Cast to ObjectId failed for value "33333630303131323233335f626e6b41636e74" (type string) at path "_id" for model "bankAccount"

Si is it possible to make 24+ character length objectId? Did I miss a configuration?


Solution

  • No, ObjectId is not just 24 bytes, but very specific 24 bytes: https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid Many frameworks (Mongoose included) rely on this.

    Saying that, _id can be of any type, not necessarily ObjectId. Can be a unique string of arbitrary length, a number, or any other BSON type.

    I find it easier to keep _id as generated ObjectId and create a separate unique index for application-level ids. Just to ensure better compatibility with tools/libraries and do not spend time debuging issues not related to work.