为什么我无法使用golang的mgo库找到ID? [英] Why can't I find the ID using the mgo library of golang?
问题描述
session.SetMode(mgo.Monotonic(mgo.Monotonic) ,true)
coll:= session.DB(aaaw_web)。C(cron_emails)
var result结果
fmt.Printf(%v,message.ID)$ (& result)
fmt.Printf(%v,结果)
fmt.Println(err)b $ b err = coll.FindId(bson.ObjectId(message.ID)
我得到这个输出:
<$ p $ b $ {ObjectIdHex()0 0 0 0 {0 false 0} 0 0 0 0 0 0 0}
ObjectIDs必须是12个字节长24)
找不到
但我查过了,文件存在于mongo中,结果,任何想法我缺少什么......
由于错误消息提示,对象ID正好是12个字节长(12个字节的数据)。您看到打印的24位长字符ID是ID的12个字节的十六进制表示(1字节=> 2位六位数字)。
使用 bson.ObjectIdHex()
功能获取 bson.ObjectId $ c $ (bson.ObjectIdHex(message.ID))。如果十六进制表示可用,那么c>
。
err = coll.FindId(bson.ObjectIdHex(message.ID ))。一个(&结果)
对于相反的方向,您可以使用 ObjectId.Hex()
方法,在这个答案中详细说明:从mgo查询获取ObjectIdHex值
您在代码中所做的是一个简单的类型转换(假设 I am using mgo library for mongo operationg in golang and here is my code : I am getting this output : But I checked, document exists in mongo, but getting here no result, any idea what am i missing ... 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 For the reverse direction, you may use the What you did in your code is a simple type conversion (given that 这篇关于为什么我无法使用golang的mgo库找到ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! message.ID
类型为 string $ c $因为基础类型
bson.ObjectId
是 string
,所以基本上可以解释24个字符为 bson.ObjectId
类型,但它是无效的 ObjectId
值,因为它将是24个字节,而不是12。 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
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)
ObjectId.Hex()
method, detailed in this answer: Obtain ObjectIdHex value from mgo querymessage.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.