首页 > 解决方案 > 无法创建/访问数据库

问题描述

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

标签: mongodbgo

解决方案


看这部分:

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

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

您可能打算这样做:

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

推荐阅读