我正在try 将文档插入到MongoDB中,但尽管成功连接到Mongo,我仍然收到以下错误:

http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference

我的Main.Go我正在初始化一个数据库连接,如下所示

func main(){
   
      //Connect to mongo
      mongoClient,err:=connectToMongo()
      if err!=nil{
          log.Panic(err)
      }
      client=mongoClient
  
      //Create a context that mongo needs in order to disconnect
      ctx,_:=context.WithTimeout(context.Background(), 15*time.Second)
     // ctx,cancel:=context.WithTimeout(context.Background(), 15*time.Second)
      //defer cancel()
      
  
      //close connection
      defer func ()  {
          if err =client.Disconnect(ctx); err!=nil{
              panic(err)
          }
      }() 

    muxRouter := mux.NewRouter().StrictSlash(true)

    //specify who's allowed to connect
    c:=cors.New(cors.Options{ 
        AllowedOrigins: []string{"https://*", "http://*"},
        AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
        ExposedHeaders: []string{"Link"},
        AllowCredentials: true,
        MaxAge: 300,
})
    router := AddRoutes(muxRouter)
    handler := c.Handler(router)
    log.Println("Service stratring at o  port ",webPort)

    sterr := http.ListenAndServe(":9090", handler) //Uncomment this line when using docker
    if sterr != nil {
        log.Fatal("error starting http server :: ", err)
        return
    }

    log.Println("Service started at port ",webPort)


    
  

}

func connectToMongo()(*mongo.Client,error){
    mongoUsername := os.Getenv("MONGOUSERNAME")
    mongoPassword := os.Getenv("MONGOPASSWORD")
    //create connection options
    clientOptions:=options.Client().ApplyURI(mongoURL)
    clientOptions.SetAuth(options.Credential{
        Username: mongoUsername,
        Password: mongoPassword,
    })

    //connect
    c,err:=mongo.Connect(context.TODO(),clientOptions)
    if err!=nil{
        log.Println("Error connecting to mongo",err)
        return nil,err
    }
    log.Println("Connected to mongo")
    return c,nil
}

在一个单独的文件中,Models.go是我try 将数据插入数据库的位置,如下所示:

var client *mongo.Client
func  Insert(entry LogEntry)error{
    log.Printf("Attempting to insert %s", entry)
    log.Printf("client s  %s", client)
    //db:=client.Database("logs")
    //log.Printf("database  is  %s", db)
    
   collection:=client.Database("logs").Collection("logsCollection")
    log.Printf("collection is  %s", collection)

    _,err :=collection.InsertOne(context.TODO(), LogEntry{
        Name: entry.Name,
        Data: entry.Data,
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    })
    if err!=nil{
        log.Println("Error inserting new record into logs collection",err)
        return err
    }
    log.Println("insert successful")
    return nil
}

有谁能发现我做错了什么吗?

推荐答案

由于该错误是一般性的(例如,未提供错误的行号),我将分享一个有效的解决方案,该解决方案或许可以帮助您找出错误所在.让我先分享一下代码.

main.go file

package main

import (
    "context"
    "fmt"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type LogEntry struct {
    Name      string
    Data      string
    CreatedAt time.Time
    UpdatedAt time.Time
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
    defer cancel()

    clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017")
    mongoClient, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        panic(err)
    }
    defer mongoClient.Disconnect(ctx)

    demoDb := mongoClient.Database("demodb")
    myCollection := demoDb.Collection("myCollection")

    // delete documents
    if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil {
        panic(err)
    }

    // insert data
    insertRes, err := myCollection.InsertOne(ctx, LogEntry{
        Name:      "lorem ipsum",
        Data:      "lorem ipsum",
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(insertRes.InsertedID)

    // query data
    cursor, err := myCollection.Find(ctx, bson.M{})
    if err != nil {
        panic(err)
    }
    var logEntries []bson.M
    if err = cursor.All(ctx, &logEntries); err != nil {
        panic(err)
    }
    for _, v := range logEntries {
        fmt.Println(v)
    }
}

出于演示的目的,我将所有逻辑放在一个文件中.在该文件中,我执行了以下步骤:

  1. 设置MongoDB连接.
  2. 连接到数据库和该数据库中的集合.
  3. 删除已经存在的所有文档(只是为了更清楚).
  4. myCollection集合中插入一个新的LogEntry实例.
  5. 检索myCollection集合中的所有条目.

最后要提的是我用来运行容器的docker命令:

docker run -d -p 27017:27017 --name mymongo -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root mongo:latest

如果您坚持使用我的解决方案,您应该能够毫无问题地插入文档.如果不是这样,请让我知道,我会尽力帮助你!

Mongodb相关问答推荐

如何使用MongoDB对子文档进行条件投影?

MongoDB/Mongoose查询:使用优先约束检索从位置A到位置B的路径

在MondoDB中:将对象数组从切片索引数组切片,并通过聚合推入数组

Mongo DB-如果一个特定字段有多个文档匹配,则更新文档字段

我无法在react 中使用 fetch 和express 从数据库中删除数据

尽管前一阶段输出文档,$group stage 仍返回零文档

错误起草的 MongoDB 聚合管道 $match 阶段

mongo shell 命令不接受使用 db 命令

MongoDB:使用数组过滤器进行更新插入

MongoDB 查询以包含多个字段的最常见值的计数

TypeError:Cannot read property '_id' of undefined

当属性确实存在时,为什么mongoose模型的 hasOwnProperty 返回 false?

MongoDB 2.1 聚合框架总和匹配名称的数组元素

MongoDB 的 BinData(0, "e8MEnzZoFyMmD7WSHdNrFJyEk8M=") 中的0是什么意思?

使用 MongoDB C# 驱动程序在嵌套数组上使用过滤器生成器进行查询

使用 mgo 存储嵌套 struct

升级mongodb

是否有适用于 Linux 的 MongoDB GUI 桌面应用程序?

Mongoose.js:嵌套属性的原子更新?

在 Ubuntu 13.10 (saucy) 中安装 Mongodb PHP 扩展的最简单方法?