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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测