Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Mongodb ObjectId to and from string automatically

I am accessing Mongo database from Clojure using Monger library. One thing that annoys me is switching back and forth between ObjectId instances and strings.

For example, the this code (mc/find-maps "posts" {}) will evaluate to maps with the value of _id entry set to instances of ObjectId class, while in my app I find it more useful to simply have it as a string for which I know that it is unique.

On the other hand for expressions like: (mc/find-map-by-id "posts" (new ObjectId id)) where I do use a String object for the id parameter, I have to use it to construct an instance of ObjectId.

Is there a way to make the values of _id convert between Strings in the application and ObjectId on the mongo side automatically and transparently? Some kind of option that, when enabled, creates maps with string representations of ids, and vice versa converts string representations of ids t object ids when used as parameters in queries?

If not, what other strategies are available?

like image 475
Goran Jovic Avatar asked Jul 13 '12 17:07

Goran Jovic


People also ask

Are MongoDB ObjectId sequential?

Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.

Can we override _id in MongoDB?

By default the _id field is of type ObjectID, one of MongoDB's BSON types. Users can also override _id to something other than an ObjectID, if desired.

Is Mongoose ObjectId a string?

MongoDB ObjectIds are typically represented using a 24 hexadecimal character string, like '5d6ede6a0ba62570afcedd3a' . Mongoose casts 24 char strings to ObjectIds for you based on your schema paths.

How does MongoDB generate ObjectId?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.


1 Answers

I share you pain on this point. Getting back ObjectID's is annoying, because you are always having to convert back and forth and if you forget then it's a hard to catch bug.

Your best bet may be to wrap the driver code to do the conversions automatically. So replace find, findOne, insert, with a thin wrapper that looks at the type and makes the conversions automatically whether you are coming in or out.

Unfortunately, I don't think there is an easier way.

like image 177
Brad C Avatar answered Oct 23 '22 13:10

Brad C