You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将环境变量传递给MongoDB驱动:Connect()函数URI解析错误

问题原因分析

你遇到的错误核心是环境变量中的URI包含了多余的双引号。虽然fmt.Println打印时看起来正常,但实际os.Getenv获取到的字符串是带双引号的(比如"mongodb+srv://..."),MongoDB驱动解析时会把开头的"当成URI scheme的一部分,导致不符合mongodb或mongodb+srv的要求。

解决方案

有两种处理方式:

方式1:修正环境变量设置

直接在设置环境变量时,去掉URI两端的双引号,示例如下:

# Linux/macOS终端
export MONGO_URI=mongodb+srv://<username>:<password>@<project-name>.mongodb.net/?retryWrites=true&w=majority

# Windows命令行
set MONGO_URI=mongodb+srv://<username>:<password>@<project-name>.mongodb.net/?retryWrites=true&w=majority

# Windows PowerShell
$env:MONGO_URI="mongodb+srv://<username>:<password>@<project-name>.mongodb.net/?retryWrites=true&w=majority"

方式2:代码中去除多余引号

如果无法修改环境变量,可以在代码里先清理URI字符串:

import "strings"

// ...

uri := strings.Trim(os.Getenv(MONGO_URI_ENV_VAR), "\"")
client, err := mongo.Connect(
    context.TODO(),
    options.Client().ApplyURI(uri),
)
if err != nil {
    log.Fatalf("mongo.Connect(): %s\n", err)
}

这样处理后,驱动就能正确识别URI的scheme了。

内容的提问来源于stack exchange,提问作者greg pinakapoging nilalang sa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:23:21