无法连接到MongoDB数据库

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

Not connecting to MongoDB database

问题

我正在尝试使用Postman向Mux Router发送POST请求。但每次我尝试发送POST请求时,Postman都会告诉我"ERROR: socket hang up"。

然后在Go中,我也收到以下错误:

http: panic serving [::1]:64995: runtime error: invalid memory address or nil pointer dereference

代码:

type Person struct {
    ID          primitive.ObjectID     `json:"_id,omitempty" bson:"_id,omitempty"`
    Firstname   string                `json:"firstname,omitempty" bson:"firstname,omitempty"`
    Lastname    string                `json:"lastname,omitempty" bson:"lastname,omitempty"`
}

var client *mongo.Client // 创建mongo客户端

func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
    w.Header().Add("Content-Type", "application/json")

    var person Person
    json.NewDecoder(r.Body).Decode(&person)

    collection := client.Database("People").Collection("people")
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    result, _:= collection.InsertOne(ctx, person)

    json.NewEncoder(w).Encode(result)
}

func main(){
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
    client.Connect(ctx)

    client.Ping(ctx, readpref.Primary())
    databases, _ := client.ListDatabaseNames(ctx, bson.M{})
    fmt.Println(databases)

    r := mux.NewRouter()

    r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")

    http.ListenAndServe(":8000", r)
}

这是我在MongoDB中创建的可用数据库:
[Hotels People admin local]

在"People"数据库下,我创建了一个"people"集合。

英文:

I am trying to do a POST request using postman to Mux Router. But each time I try to do the POST request, PostMan always tells me "ERROR: socket hang up".

Then in Go I also receive the following error:

http: panic serving [::1]:64995: runtime error: invalid memory address or nil pointer dereference

Code:

type Person struct {
	ID 			primitive.ObjectID 	`json:"_id,omitempty" bson:"_id,omitempty"`
	Firstname 	string				`json:"firstname,omitempty" bson:"firstname,omitempty"`
	Lastname	string				`json:"lastname,omitempty" bson:"lastname,omitempty"`
}

var client *mongo.Client // create mongo client

func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
	w.Header().Add("Content-Type", "application/json")

	var person Person
	json.NewDecoder(r.Body).Decode(&person)

	collection := client.Database("People").Collection("people")
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	result, _:= collection.InsertOne(ctx, person)

	json.NewEncoder(w).Encode(result)
}

func main(){
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
	client.Connect(ctx)

	client.Ping(ctx, readpref.Primary())
	databases, _ := client.ListDatabaseNames(ctx, bson.M{})
	fmt.Println(databases)

	r := mux.NewRouter()

	r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")

	http.ListenAndServe(":8000", r)
}

Here are the available Databases I have created in MongoDB:
[Hotels People admin local]

Under the "People" Database I created a "people" collection.

答案1

得分: 3

你在main函数中使用:=运算符创建了一个新的client变量。请使用=将其赋值给全局的client变量。

英文:

You're creating a new client variable in your main function with the := operator. Use = to assign to your global client variable.

huangapple
  • 本文由 发表于 2021年6月28日 14:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/68158511.html
匿名

发表评论

匿名网友

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

确定