无法使用mgo从MongoDB通过ObjectId获取数据。

huangapple go评论72阅读模式
英文:

Can not get data by ObjectId from MongoDB using mgo

问题

我有一个PersonalAccount类型,如下所示:

type PersonalAccount struct {
    ID bson.ObjectId `json:"id" bson:"_id,omitempty"`
}

然后,我通过HTTP请求获取了一个序列化的PersonalAccount,并成功反序列化数据后,当我检查ID的类型时,它是一个bson.ObjecID

问题是,当我尝试以下代码时:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").FindId(m.ID)

它返回一个错误,说找不到。

我还尝试了以下代码:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").Find(bson.M{"_id": m.ID})

但没有成功。

英文:

I have a PersonalAccount type as

type PersonalAccount struct {
        ID        bson.ObjectId   `json:"id" bson:"_id,omitempty"`
}

then I get a marshaled PersonalAccount through an HTTP request, and the data is unmarshaled successfully and when I check the ID type.
It is a bson.ObjecID

The problem is when I try the code below:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").FindId(m.ID)

It returns an error that says it is not found.

I have also tried:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").Find(bson.M{"_id": m.ID})

but with no luck.

答案1

得分: 0

你可以尝试这样做:

c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})

也许这能解决你的问题。

英文:

You can try this

c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})

may be it will solve your problem

huangapple
  • 本文由 发表于 2017年1月21日 19:26:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/41778758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定