Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  104] [ 5]  / answers: 1 / hits: 132388  / 12 Years ago, thu, december 13, 2012, 12:00:00

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

More From » node.js

 Answers
10

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.


[#81455] Tuesday, December 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;