Mongodb 无法创建/访问数据库

Mongodb 无法创建/访问数据库,mongodb,go,Mongodb,Go,我在Python中一直使用MongoDB,但现在需要在go中构建一个客户端。 我已经阅读了文档,示例工作正常。 但是当我尝试使用自己的代码时,代码执行时不会出错,但是当我检查数据库(通过CLI)时,我没有看到任何数据库、集合和数据 我肯定我做错了什么,但我无法在这个小测试代码中找到它 func main() { if client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")

我在Python中一直使用MongoDB,但现在需要在go中构建一个客户端。 我已经阅读了文档,示例工作正常。
但是当我尝试使用自己的代码时,代码执行时不会出错,但是当我检查数据库(通过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)
    }
}
看看这部分:

if err = client.Connect(ctx); err == nil {
  os.Exit(0)
}
如果您能够连接到我们(
err
nil
),您将退出

你可能想做:

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

我觉得自己很愚蠢。。。。“是时候休息一下了,而不是为这里的人浪费时间了。@Francesco那样很容易失明。”。已经有人这么做了。记录仍然没有被存储,肯定是另一个打字错误。谢谢