英文:
Can't get FindId to work (GO + MGO)
问题
不确定这里发生了什么...但是我试图完成一个简单的操作时遇到了很大的困难。我刚开始学习GO(试图从Node切换过来),所以可能是类型的问题...
User struct {
ID_ bson.ObjectId `bson:"_id,omitempty" json:"_id,omitempty"`
UTC time.Time `bson:"utc,omitempty" json:"utc,omitempty"`
USR string `bson:"usr,omitempty" json:"usr,omitempty"`
PWD string `bson:"pwd,omitempty" json:"pwd,omitempty"`
}
func save(w http.ResponseWriter, r *http.Request) {
m := s.Copy()
defer m.Close()
user := m.DB("0").C("user")
var a User
json.NewDecoder(r.Body).Decode(&a)
err := user.FindId(a.ID_)
if err != nil {
panic(err)
}
}
这会返回以下错误
http: panic serving [::1]:53092: &{{0 0} 0xc208062600 {{0.user [{_id TE?????}] 0 0 ?
reflect.Value? 0 <nil> {?reflect.Value? ?reflect.Value? ?reflect.Value? false false [] 0}
false []} 0.25 0}}
当我运行:
a.ID_.Valid()
我得到了"true"。
附注:我可以让这个工作起来:
func user(w http.ResponseWriter, r *http.Request) {
m := s.Copy()
defer m.Close()
user := m.DB("0").C("user")
a := &User{ID_:bson.NewObjectId(), UTC:time.Now()}
b, _ := json.Marshal(a)
user.Insert(a)
}
非常感谢任何帮助。
英文:
Not sure what's going on here... but I'm having a heck of a time trying to get a simple operation done. I'm new to GO (trying to switch from Node) so it's probably a Type thing...
User struct {
ID_ bson.ObjectId `bson:"_id,omitempty" json:"_id,omitempty"`
UTC time.Time `bson:"utc,omitempty" json:"utc,omitempty"`
USR string `bson:"usr,omitempty" json:"usr,omitempty"`
PWD string `bson:"pwd,omitempty" json:"pwd,omitempty"`
}
func save(w http.ResponseWriter, r *http.Request) {
m := s.Copy()
defer m.Close()
user := m.DB("0").C("user")
var a User
json.NewDecoder(r.Body).Decode(&a)
err := user.FindId(a.ID_)
if err != nil {
panic(err)
}
}
This returns the following error
http: panic serving [::1]:53092: &{{0 0} 0xc208062600 {{0.user [{_id TE?????}] 0 0 ?
reflect.Value? 0 <nil> {?reflect.Value? ?reflect.Value? ?reflect.Value? false false [] 0}
false []} 0.25 0}}
When I run:
a.ID_.Valid()
I get "true".
PS. I can get this to work:
func user(w http.ResponseWriter, r *http.Request) {
m := s.Copy()
defer m.Close()
user := m.DB("0").C("user")
a := &User{ID_:bson.NewObjectId(), UTC:time.Now()}
b, _ := json.Marshal(a)
user.Insert(a)
}
Any help would be really appreciated.
答案1
得分: 4
FindId 方法返回一个 Query 对象,而不是一个错误。调用 Query 的 One 方法来获取文档。
答案2
得分: 3
根据文档 http://godoc.org/labix.org/v2/mgo#Collection.FindId
FindId
返回一个 Query
结构体,你可以在其上调用任何函数。FindId
不会返回错误。
尝试使用以下代码:
var userDoc interface{}
if err := user.FindId(a.ID_).One(&userDoc); err != nil {
panic(err)
}
你可以将 interface{}
替换为你用于用户的任何结构体。
英文:
As per the docs http://godoc.org/labix.org/v2/mgo#Collection.FindId
FindId
returns a Query
struct which you can then call any of its functions. FindId
does not return an error.
Try
var userDoc interface{}
if err := user.FindId(a.ID_).One(&userDoc); err != nil {
panic(err)
}
You can change interface{}
with whatever struct you are using for users.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论