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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP