How to check that mongo ObjectID is valid in python?

Salvador Dali picture Salvador Dali · Feb 27, 2015 · Viewed 9.7k times · Source

I want to verify that the objectID is a valid mongoID string.

Currently I have:

import bson
try:
  bson.objectid.ObjectId(id)
except:
  pass # do something

I wanted to make my exception more specific, and it looks like there is a solution, but except bson.objectid.InvalidId ends up in TypeError: id must be an instance of (str, unicode, ObjectId).

Ok, I tried to look further and found is_valid method but bson.is_valid(1) results in another error TypeError: BSON data must be an instance of a subclass of str.

So how can I properly check if my objectID is valid?

Answer

shx2 picture shx2 · Feb 28, 2015

I think you're confusing bson.is_valid() with bson.objectid.ObjectId.is_valid().

The latter works for me.

bson.objectid.ObjectId.is_valid('54f0e5aa313f5d824680d6c9')
=> True
bson.objectid.ObjectId.is_valid('54f0e5aa313f5d824680d')
=> False

Its implementation is more or less what you'd expect:

@classmethod
def is_valid(cls, oid):
    try:
        ObjectId(oid)
        return True
    except (InvalidId, TypeError):
        return False