Go和MongoDb错误:没有字段或方法

时间:2016-01-28 06:56:09

标签: mongodb go bson

我是Golang的新手。在尝试从MongoDb查询结果中提取password时,我收到以下错误:

  

“./ 1.go:73:results.password undefined(type [] 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)
}

1 个答案:

答案 0 :(得分:1)

您的results变量是Person s的片段:

var results []Person

PasswordPerson的字段。所以这一行:

fmt.Println("New Password ", results.password)

是编译时错误,因为password不是[]Person类型的字段(或方法)(另请注意passwordPassword不同)。< / p>

您可以像这样引用切片的第一个元素:

if len(results) > 0 {
    fmt.Println("New Password:", results[0].Password)
} else {
    fmt.Println("No peope")
}