通过ID从集合中检索文档。

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

Retrieving document from collection by id

问题

我在这里为您翻译代码部分:

我在收藏中拥有的对象:

type Room struct {
    Id bson.ObjectId            `json:"Id"              	bson:"_id"`
    Name string                 `json:"Name"            	bson:"name"`
}

插入到收藏中:

room = &Room{Id: bson.NewObjectId(), Name: "test"}
RoomCollection.Insert(room)

从收藏中检索(任意):

roomX := &Room{}
if err := RoomCollection.Find(bson.M{}).One(roomX); err != nil {
    panic(err)
}
fmt.Printf("RoomX %s:\n%+v\n\n", roomX.Id, roomX)

这将输出:

RoomX ObjectIdHex("52024f457a7ea6334d000001"):
&{Id:ObjectIdHex("52024f457a7ea6334d000001") Name:test}

从收藏中检索(按id):

roomZ := &Room{}
if err := RoomCollection.Find(bson.M{"_id": room.Id}).One(roomZ); err != nil {
    panic(err) // 抛出 "not found"
}

这会抛出 "not found",我无法弄清楚为什么。

英文:

My object I have in collection:

type Room struct {
    Id bson.ObjectId            `json:"Id"              	bson:"_id"`
    Name string                 `json:"Name"            	bson:"name"`
}

Inserting into collection:

room = &Room{Id: bson.NewObjectId(), Name: "test"}
RoomCollection.Insert(room)

Retrieving from collection (any):

roomX := &Room{}
if err := RoomCollection.Find(bson.M{}).One(roomX); err != nil {
    panic(err)
}
fmt.Printf("RoomX %s:\n%+v\n\n", roomX.Id, roomX)

This outputs:

RoomX ObjectIdHex("52024f457a7ea6334d000001"):
&{Id:ObjectIdHex("52024f457a7ea6334d000001") Name:test}

Retrieving from collection (by id):

roomZ := &Room{}
if err := RoomCollection.Find(bson.M{"_id": room.Id}).One(roomZ); err != nil {
    panic(err) // throws "not found"
}

This throws "not found" and I can't figure out why.

答案1

得分: 2

字段的不同键值标签应该根据reflect包的规定用空格分隔。

按照惯例,标签字符串是可选地用空格分隔的键:"值"对的串联。每个键是一个非空字符串,由非控制字符组成,除了空格(U+0020 ' ')、引号(U+0022 '"')和冒号(U+003A ':')。每个值使用U+0022 '"'字符和Go字符串字面值语法进行引用。

mgo包无法读取标签,并将Id的值存储为id而不是_id

英文:

The different key-value tags for a field should, according to the reflect package, be separated with space.

>By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

The mgopackage fails to read the tag and stores the Id value as id instead of _id.

huangapple
  • 本文由 发表于 2013年8月7日 21:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/18105411.html
匿名

发表评论

匿名网友

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

确定