我可以确定一个字符串是否是MongoDB ObjectID? [英] Can I determine if a string is a MongoDB ObjectID?

查看:645
本文介绍了我可以确定一个字符串是否是MongoDB ObjectID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过将字符串转换为BSON来进行MongoDB查找。有没有办法确定我有一个有效的ObjectID为Mongo在做转换之前?



这是我当前的findByID函数的coffeescript。它工作的很好,但我想查找不同的属性,如果我确定字符串不是一个ID。

  db .collectionpages,(err,collection) - > 
collection.findOne
_id:new BSON.ObjectID(id)
,(err,item) - >
if item
res.send item
else
res.send 404


<我发现,mongoose ObjectId验证器工作来验证有效的objectIds,但我发现一些情况下,无效的id被认为是有效的。 (例如:任何12位字符串)

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

对我有用的是将一个字符串转换为一个objectId,然后检查原始字符串匹配objectId的字符串值。

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

ids在投射到ObjectId时不会更改,但当转换为objectId时,将更改获取false有效的字符串。


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

解决方案

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 digit 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.

这篇关于我可以确定一个字符串是否是MongoDB ObjectID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆