我可以确定一个字符串是否是 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 函数的咖啡脚本.它很好用,但如果我确定字符串不是 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 验证器可以验证有效的 objectId,但我发现在少数情况下无效的 id 被认为是有效的.(例如:任何 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
之所以有效,是因为有效 id 在转换为 ObjectId 时不会更改,但如果字符串为 false 有效,则会在转换为 objectId 时发生更改.
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.
相关文章