douwei7501 2013-08-07 13:57
浏览 42
已采纳

按ID从集合中检索文档

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:
%+v

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

  • dongpengyu1363 2013-08-07 14:17
    关注

    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.

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

    报告相同问题?

    悬赏问题

    • ¥50 vue-codemirror如何对指定行 指定位置的 字符进行背景颜色或者字体颜色的修改?
    • ¥15 有人会思科模拟器嘛?
    • ¥30 遇到一个的问题,请教各位
    • ¥20 matlab报错,vflux计算潜流通量
    • ¥15 我该如何实现鼠标按下GUI按钮时就执行按钮里面的操作的方法
    • ¥15 关于#硬件工程#的问题:我这边有个锁相环电路没有效果
    • ¥15 20款 27寸imac苹果一体机装win10后,蓝牙耳机和音响放歌曲卡顿断断续续.
    • ¥15 VB.NET 父窗体调取子窗体报错
    • ¥15 python海龟作图如何改代码使其最后画出来的是一个镜像翻转的图形
    • ¥15 我不明白为什么c#微软的官方api浏览器为什么不支持函数说明的检索,有支持检索函数说明的工具吗?