无法连接到MongoDB数据库

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

Not connecting to MongoDB database

问题

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

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

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

代码:

  1. type Person struct {
  2. ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
  3. Firstname string `json:"firstname,omitempty" bson:"firstname,omitempty"`
  4. Lastname string `json:"lastname,omitempty" bson:"lastname,omitempty"`
  5. }
  6. var client *mongo.Client // 创建mongo客户端
  7. func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
  8. w.Header().Add("Content-Type", "application/json")
  9. var person Person
  10. json.NewDecoder(r.Body).Decode(&person)
  11. collection := client.Database("People").Collection("people")
  12. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  13. result, _:= collection.InsertOne(ctx, person)
  14. json.NewEncoder(w).Encode(result)
  15. }
  16. func main(){
  17. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  18. client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
  19. client.Connect(ctx)
  20. client.Ping(ctx, readpref.Primary())
  21. databases, _ := client.ListDatabaseNames(ctx, bson.M{})
  22. fmt.Println(databases)
  23. r := mux.NewRouter()
  24. r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
  25. http.ListenAndServe(":8000", r)
  26. }

这是我在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:

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

Code:

  1. type Person struct {
  2. ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
  3. Firstname string `json:"firstname,omitempty" bson:"firstname,omitempty"`
  4. Lastname string `json:"lastname,omitempty" bson:"lastname,omitempty"`
  5. }
  6. var client *mongo.Client // create mongo client
  7. func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
  8. w.Header().Add("Content-Type", "application/json")
  9. var person Person
  10. json.NewDecoder(r.Body).Decode(&person)
  11. collection := client.Database("People").Collection("people")
  12. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  13. result, _:= collection.InsertOne(ctx, person)
  14. json.NewEncoder(w).Encode(result)
  15. }
  16. func main(){
  17. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  18. client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
  19. client.Connect(ctx)
  20. client.Ping(ctx, readpref.Primary())
  21. databases, _ := client.ListDatabaseNames(ctx, bson.M{})
  22. fmt.Println(databases)
  23. r := mux.NewRouter()
  24. r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
  25. http.ListenAndServe(":8000", r)
  26. }

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:

确定