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

huangapple go评论95阅读模式
英文:

Go and MongoDb Error: has no field or method

问题

我是新手,正在尝试从MongoDb查询结果中提取password,但是遇到了以下错误:

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

错误是由代码中倒数第二行引起的。

我们如何分离查询结果?

代码:

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)

		//下一行引起错误....
		fmt.Println("New Password ", results.password)

	})

	http.ListenAndServe(":9000", nil)
}

请注意,错误是因为在results上使用了password字段,但是results是一个[]Person类型的切片,没有password字段。你可以通过遍历results切片来访问每个Person对象的Password字段。

英文:

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

得分: 1

你的results变量是一个Person的切片:

var results []Person

PasswordPerson的一个字段。所以这行代码:

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

是一个编译时错误,因为password不是[]Person类型的字段(或方法)(还要注意passwordPassword是不同的)。

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

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

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")
}

huangapple
  • 本文由 发表于 2016年1月28日 14:56:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/35054694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定