mongodb - 无法创建/访问数据库
问题描述
我在 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)
}
}
解决方案
看这部分:
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)
}
推荐阅读
- javascript - 如何从 Javascript 输出中删除这些引号?
- powershell - 从 powershell 或 cmd 获取带有空格的显示名称 - 仅限 AzuredAD
- java - 给出15-puzzle棋盘的一部分,如何使用BFS获取该部分棋盘的所有状态?
- excel - 我想使用 Excel 索引和匹配公式,但是我想排除结果
- matplotlib - matplotlib - 注释行与起点和终点不完全匹配
- wordpress - 我想定制一个插件以满足我的要求;我的要求是为向上投票和向下投票添加向上箭头和向下箭头
- matlab - MATLAB fmincon 如何在有限差分步长上如此稳健?
- javascript - NestJs 创建用于记录的自定义服务 - 不打印输出
- php - 无法使 ghostscript 在 moodle 3.9 上工作
- json - 尝试通过 API 更新 Webex 用户时出现 400 错误