Question

Is it possible to recognize if a string is formatted as a BSON ObjectID?

For strings we could do:

"hello".is_a?(String) # => true

That would not work since the ObjectID is a String anyway. But is it possible to analyze the string to determine if it's formatted as a BSON ObjectID?

Usually, ObjectIDs have this format.

  52f4e2274d6f6865080c0000

The formatting criteria is stated in the docs:

ObjectId is a 12-byte BSON type, constructed using:

a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

Was it helpful?

Solution

Any 24 chararcters long hexadecimal string is a valid BSON object id, so you can check it using this regular expression:

'52f4e2274d6f6865080c0000' =~ /\A\h{24}\z/
# => 0

Both the moped (used by mongoid) and the bson (used by mongo_mapper) gems encapsulates this check in a legal? method:

require 'moped'
Moped::BSON::ObjectId.legal?('00' * 12)
# => true


require 'bson'
BSON::ObjectId.legal?('00' * 12)
# => true

OTHER TIPS

In Mongoid use: .is_a?(Moped::BSON::ObjectId) sytanx.

Example:

some_id = YourModel.first.id
some_id.is_a?(Moped::BSON::ObjectId)

Note:

"52d7874679478f45e8000001".is_a?(String) # Prints true

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top