我可以确定一个字符串是否是MongoDB ObjectID? [英] Can I determine if a string is a MongoDB ObjectID?
问题描述
我正在通过将字符串转换为BSON来进行MongoDB查找。在进行转换之前,有没有办法确定我的字符串是否为Mongo的有效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?
这是我当前findByID函数的coffeescript。它的效果非常好,但是如果我确定字符串不是ID,我想要查找不同的属性。
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
推荐答案
我发现mongoose ObjectId验证器用于验证有效的objectIds,但是发现有几种情况被认为是有效的。 (例如:任意12个字符的长字符串)
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
为我工作的是将一个字符串转换为一个objectId,然后检查原始字符串匹配objectId的字符串值。
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
ids在转换为ObjectId时不会更改,但是当转换为objectId时,将变为false的字符串将更改。
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.
这篇关于我可以确定一个字符串是否是MongoDB ObjectID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!