英文:
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 mgo
package fails to read the tag and stores the Id value as id
instead of _id
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论