为什么使用golang的mgo库找不到id?
Why can't I find the ID using the mgo library of golang?
我在 golang 中使用 mgo 库进行 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,但没有得到任何结果,不知道我错过了什么......
正如错误消息提示的那样,一个对象 ID 正好是 12 个字节长(12 个字节的数据)。您看到打印的 24 个字符长的 ID 是 ID 的 12 个字节的十六进制表示(1 个字节 => 2 个十六进制数字)。
如果十六进制表示可用,请使用 bson.ObjectIdHex()
function to obtain a value of bson.ObjectId
。
err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
反方向可以使用ObjectId.Hex()
method, detailed in this answer:
您在代码中所做的是一个简单的 type conversion(假定 message.ID
的类型为 string
),并且语法有效,因为 [=12] 的基础类型=] 是 string
,所以这基本上将 24 个字符解释为 bson.ObjectId
类型,但它是一个无效的 ObjectId
值,因为它将是 24 个字节而不是 12.
我在 golang 中使用 mgo 库进行 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,但没有得到任何结果,不知道我错过了什么......
正如错误消息提示的那样,一个对象 ID 正好是 12 个字节长(12 个字节的数据)。您看到打印的 24 个字符长的 ID 是 ID 的 12 个字节的十六进制表示(1 个字节 => 2 个十六进制数字)。
如果十六进制表示可用,请使用 bson.ObjectIdHex()
function to obtain a value of bson.ObjectId
。
err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
反方向可以使用ObjectId.Hex()
method, detailed in this answer:
您在代码中所做的是一个简单的 type conversion(假定 message.ID
的类型为 string
),并且语法有效,因为 [=12] 的基础类型=] 是 string
,所以这基本上将 24 个字符解释为 bson.ObjectId
类型,但它是一个无效的 ObjectId
值,因为它将是 24 个字节而不是 12.