无法使用Golang / MongoDB创建/访问数据库

问题描述 投票:0回答:1

我一直在使用MongoDB,但在Python中没有问题,但是现在我需要立即构建一个客户端。我看了看文档,例子很好用。但是,当我尝试使用自己的代码时,该代码执行时没有错误,但是,当我(通过CLI)检查数据库时,看不到任何数据库,集合和数据。

我确定我做错了什么,但是在这个小的测试代码中找不到。

func main() {

    if client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")); err == nil {
        ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
        defer client.Disconnect(ctx)
        if err = client.Connect(ctx); err == nil {
            os.Exit(0)
        }

        KeysCol := client.Database("yfroot").Collection("KeysCol")

        mac, e1 := crypto.GenerateRandomBytes(16)
        key, e2 := crypto.GenerateRandomBytes(16)
        if e1 != nil || e2 != nil {
            fmt.Println("failed crypto generate")
            os.Exit(0)
        }
        testKey := dataformats.DeviceKey{
            Mac: string(mac),
            Key: key,
        }

        // ctx, _ = context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
        _, err := KeysCol.InsertOne(ctx, testKey)
        if err != nil {
            fmt.Println(err)
            os.Exit(0)
        }

    } else {
        fmt.Println(err)
    }
}

感谢您的帮助!

关闭:这是该死的错字...。

mongodb go
1个回答
1
投票

查看此部分:

if err = client.Connect(ctx); err == nil {
  os.Exit(0)
}

如果您能够连接我们(errnil),您正在退出。

您可能想这样做:

if err = client.Connect(ctx); err != nil {
  fmt.Println(err)
  os.Exit(0)
}
© www.soinside.com 2019 - 2024. All rights reserved.