首页 > 后端开发 > Golang > 正文

Golang无法在MongoDB中创建文档

WBOY
发布: 2024-02-12 14:42:07
转载
620 人浏览过

Golang无法在MongoDB中创建文档

问题内容

我正在尝试将文档插入 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 中,我尝试将数据插入数据库,如下所示:

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 文件

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运行-d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest

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

以上是Golang无法在MongoDB中创建文档的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!