dongque1646 2018-05-09 08:08
浏览 40

mongoDB Golang Bson界面有问题吗?

I uesd MongoDB v3.6.4 with mgo(gopkg.in/mgo.v2) package

Bson

var id interface{}  
id = 249678041972736  
bson.M{"_id": id}  
var id int64  
id = 249678041972736  
bson.M{"_id": id}

Tow bsons are not same?
eg:

func GetUser(id interface{}) (*User, error) {  
    session := MongoDB()  
    defer session.Close()  
    var m *User  
    err := session.DB.C("user").Find(&bson.M{"_id": id}).One(&m)  
    // !!!err: not found  
    if err != nil {  
        return nil, err  
    } else {  
        return m, nil  
    }
}  

but:

func GetUser(id int64) (*User, error) {  
    session := MongoDB()  
    defer session.Close()  
    var m *User  
    err := session.DB.C("user").Find(&bson.M{"_id": id}).One(&m)  
    // !!! err == nil 
    if err != nil {  
        return nil, err  
    } else {  
        return m, nil  
    }
}  

GetUser(id interface{}) can get err (not found)  
GetUser(id int64) can get nil err 

Pay attention to error

I used function GetUser and import same value 249678041972736 but different parameter type get differents result

why???

  • 写回答

1条回答 默认 最新

  • dongyingming8970 2018-05-09 12:37
    关注

    You are putting an unnecessary & in front of the bson.M{…

    err := session.DB.C("user").Find(bson.M{"_id": id}).One(&m)
    

    The use of bson.M in the find is also unnecessary, mgo has a call of FindId specifically for the search you are doing.

    err := session.DB.C("user").FindId(id).One(&m)
    

    gopkg.in/mgo.v2 is now marked as unmaintained. github.com/globalsign/mgo and github.com/globalsign/mgo/bson are the two maintained forked libraries. I have found no problems using them instead pf gopkg.in

    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作