我是 Golang 的新手。在尝试password从 MongoDb 查询结果中提取时,出现以下错误:
“./1.go:73: results.password 未定义(类型 []Person 没有字段或方法密码)”
该错误是由代码中的倒数第二行引起的。
我们如何分离查询结果?
代码:
package main
import ("fmt""html/template""log""net/http""reflect""gopkg.in/mgo.v2/bson""gopkg.in/mgo.v2")
type login struct {
UserName string
Password string
}
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
FirstName string
LastName string
Email string
Password string
}
func main() {
// DB Connection
session, err := mgo.Dial(":27017")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("reg").C("people")
session.SetMode(mgo.Monotonic, true)
// parse template
tpl, err := template.ParseFiles("Login.html")
if err != nil {
log.Fatalln(err)
}
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
// receive form submission
uname := req.FormValue("username")
pwd := req.FormValue("password")
fmt.Println("fName: ", uname)
fmt.Println("[]byte(uname): ", []byte(uname))
fmt.Println("typeOf: ", reflect.TypeOf(uname))
fmt.Println("pwd : ", pwd)
fmt.Println("[]byte(pwd ): ", []byte(pwd))
fmt.Println("typeOf: ", reflect.TypeOf(pwd))
// execute template
err = tpl.Execute(res, login{uname,pwd})
if err != nil {
http.Error(res, err.Error(), 500)
log.Fatalln(err)
}
//DB access
var results []Person
err = c.Find(bson.M{"firstname": uname}).Sort("-id").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
//Next Line Causes Error....
fmt.Println("New Password ", results.password)
})
http.ListenAndServe(":9000", nil)
}
Qyouu
相关分类