英文:
Why can't I find the ID using the mgo library of golang?
问题
我正在使用mgo库在golang中进行Mongo操作,以下是我的代码:
session.SetMode(mgo.Monotonic, true)
coll := session.DB("aaaw_web").C("cron_emails")
var result Result
fmt.Printf("%v", message.ID)
err = coll.FindId(bson.ObjectId(message.ID)).One(&result)
fmt.Printf("%v", result)
fmt.Println(err)
我得到了以下输出:
595f2c1a6edcba0619073263
{ObjectIdHex("") 0 0 0 0 {0 false 0} 0 0 0 0 0 0 0}
ObjectIDs must be exactly 12 bytes long (got 24)
not found
但是我检查了一下,在Mongo中存在该文档,但是这里没有返回结果,你有什么想法,我漏掉了什么...
英文:
I am using mgo library for mongo operationg in golang and here is my code :
session.SetMode(mgo.Monotonic, true)
coll := session.DB("aaaw_web").C("cron_emails")
var result Result
fmt.Printf("%v", message.ID)
err = coll.FindId(bson.ObjectId(message.ID)).One(&result)
fmt.Printf("%v", result)
fmt.Println(err)
I am getting this output :
595f2c1a6edcba0619073263
{ObjectIdHex("") 0 0 0 0 { 0 false 0 } 0 0 0 0 0 0 0}
ObjectIDs must be exactly 12 bytes long (got 24)
not found
But I checked, document exists in mongo, but getting here no result, any idea what am i missing ...
答案1
得分: 15
正如错误消息所提示的,对象ID的长度为12个字节(12个数据字节)。你在打印出来的24个字符的ID是ID的十六进制表示(1个字节 => 2个十六进制数字)。
如果有十六进制表示可用,可以使用bson.ObjectIdHex()
函数获取bson.ObjectId
的值。
err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
要进行反向转换,可以使用ObjectId.Hex()
方法,详细信息可以参考这个答案:https://stackoverflow.com/questions/29146922/obtain-objectidhex-value-from-mgo-query/29148800#29148800
你在代码中所做的是一个简单的类型转换(假设message.ID
的类型是string
),语法是有效的,因为bson.ObjectId
的底层类型是string
,所以它基本上将这24个字符解释为bson.ObjectId
类型,但它是一个无效的ObjectId
值,因为它将是24个字节而不是12个字节。
英文:
As the error message hints, an object id is exactly 12 bytes long (12 bytes of data). The 24 char long ID you see printed is the hexadecimal representation of the 12 bytes of the ID (1 byte => 2 hexa digits).
Use the bson.ObjectIdHex()
function to obtain a value of bson.ObjectId
if the hex representation is available.
err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
For the reverse direction, you may use the ObjectId.Hex()
method, detailed in this answer: https://stackoverflow.com/questions/29146922/obtain-objectidhex-value-from-mgo-query/29148800#29148800
What you did in your code is a simple type conversion (given that message.ID
is of type string
), and the syntax is valid because the underlying type of bson.ObjectId
is string
, so that basically interprets the 24 characters as bson.ObjectId
type, but it is an invalid ObjectId
value because it will be 24 bytes and not 12.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论