douyan1321 2016-01-28 06:56
浏览 52
已采纳

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

I am new in Golang. While trying to extract password from the MongoDb query result, I got the following error:

"./1.go:73: results.password undefined (type []Person has no field or method password)"

The error is caused by the second last line in the code.

How can we separate the query result?

Code:

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

  • dtvgo28624 2016-01-28 06:59
    关注

    Your results variable is a slice of Persons:

    var results []Person
    

    Password is a field of Person. So this line:

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

    Is a compile time error because password is not a field (or method) of the type []Person (also note that password is different from Password).

    You may refer to the first element of the slice like this:

    if len(results) > 0 {
        fmt.Println("New Password:", results[0].Password)
    } else {
        fmt.Println("No peope")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码