Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine if a string is a MongoDB ObjectID?

I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?

Here is the coffeescript for my current findByID function. It works great, but I'd like to lookup by a different attribute if I determine the string is not an ID.

db.collection "pages", (err, collection) ->   collection.findOne     _id: new BSON.ObjectID(id)   , (err, item) ->     if item       res.send item     else       res.send 404 
like image 216
Will Avatar asked Dec 13 '12 00:12

Will


People also ask

Can MongoDB _id be a string?

Yes, you can use a string as your _id.

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.

What is the datatype for ObjectId?

Binary JSON (BSON)

How does MongoDB compare ObjectId?

Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the . equals() method. With your example, results.


1 Answers

I found that the mongoose ObjectId validator works to validate valid objectIds but I found a few cases where invalid ids were considered valid. (eg: any 12 characters long string)

var ObjectId = require('mongoose').Types.ObjectId; ObjectId.isValid('microsoft123'); //true ObjectId.isValid('timtomtamted'); //true ObjectId.isValid('551137c2f9e1fac808a5f572'); //true 

What has been working for me is casting a string to an objectId and then checking that the original string matches the string value of the objectId.

new ObjectId('timtamtomted'); //616273656e6365576f726b73 new ObjectId('537eed02ed345b2e039652d2') //537eed02ed345b2e039652d2 

This work because valid ids do not change when casted to an ObjectId but a string that gets a false valid will change when casted to an objectId.

like image 177
Andy Macleod Avatar answered Oct 06 '22 01:10

Andy Macleod