Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that mongo ObjectID is valid in python?

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?

like image 622
Salvador Dali Avatar asked Feb 27 '15 21:02

Salvador Dali


People also ask

How do you check MongoDB ID is valid or not?

isValidObjectId = function(v) { if (v == null) { return true; } //Other code if (v. toString instanceof Function) { v = v. toString(); } if (typeof v === 'string' && v. length === 12) { return true; } //Other code return false; };

How do you check if the object ID is valid or not?

isValidObjectId() is most commonly used to test a expected objectID, in order to avoid mongoose throwing invalid object ID error. if (mongoose. isValidObjectId("some 12 byte string")) { return collection. findOne({ _id: "some 12 byte string" }) // returns null if no record found. }

Is MongoDB an ObjectId?

Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>). An ObjectId is a 12-byte BSON type hexadecimal string having the structure as shown in the example below.

Is MongoDB ObjectId ordered?

No. Since ObjectIDs are typically generated on the client, the deployment topology does not factor into the ordering of ObjectIDs. Even if the ObjectIDs are generated on the server, multiple ObjectIDs generated in the same second will not have a predictable ordering.


2 Answers

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
like image 64
shx2 Avatar answered Oct 21 '22 20:10

shx2


This is what works for me :

from bson import ObjectId

if ObjectId.is_valid("5bb3314919802578051ccf86"):
  return True
else:
  return False
like image 2
Ninad Kulkarni Avatar answered Oct 21 '22 19:10

Ninad Kulkarni