dousong2023 2017-07-07 08:55
浏览 292
已采纳

为什么我无法使用golang的mgo库找到ID?

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条回答 默认 最新

  • douao8353 2017-07-07 11:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组