我收藏的物品:
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) // throws "not found"
}
这会抛出“未找到”,我不知道为什么。