为什么我无法使用golang的mgo库找到ID? [英] Why can't I find the ID using the mgo library of golang?

查看:1119
本文介绍了为什么我无法使用golang的mgo库找到ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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

  err = coll.FindId(bson.ObjectIdHex(message.ID ))。一个(&结果)

对于相反的方向,您可以使用 ObjectId.Hex() 方法,在这个答案中详细说明:从mgo查询获取ObjectIdHex值



您在代码中所做的是一个简单的类型转换(假设 message.ID 类型为 string bson.ObjectId string ,所以基本上可以解释24个字符为 bson.ObjectId 类型,但它是无效的 ObjectId 值,因为它将是24个字节,而不是12。

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

解决方案

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: Obtain ObjectIdHex value from mgo query

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.

这篇关于为什么我无法使用golang的mgo库找到ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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