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?
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; };
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. }
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.
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.
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
This is what works for me :
from bson import ObjectId
if ObjectId.is_valid("5bb3314919802578051ccf86"):
return True
else:
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With