skip to Main Content

hello everyone 🙂 noob here

how come i get this error message from the mongodb driver’s Connect() function

i have this code:

        // this Println() works fine
    fmt.Println(os.Getenv(MONGO_URI_ENV_VAR))

    client, err := mongo.Connect(  // this is where it's erroring out 
        context.TODO(),
        options.Client().ApplyURI(os.Getenv(MONGO_URI_ENV_VAR)),
    )
    if err != nil {
        log.Fatalf("mongo.Connect(): %sn", err)
    }

and i get the printline of the api key from the env var fine
but the mongo.Connect() function errors out saying:

2023/07/22 21:47:25 mongo.Connect(): error parsing uri: scheme must be "mongodb" or "mongodb+srv"

the url looks something like this btw:

"mongodb+srv://<username>:<password>@<project-name>.mongodb.net/?retryWrites=true&w=majority"

additional info:
when i pass just a regular string instead of getting value of the envar and passing that into the ApplyURI() method, it works. but i’d rather not commit that to the repo nomsayin

2

Answers


  1. Chosen as BEST ANSWER

    figured it out, i was passing single quotes to env var through the shell, I thought that's you're supposed to do it coz the shell would parse the reserved characters like this:

    MONGO_URI='mongodb+srv://<username>:<password>@<project-name>.mongodb.net/?retryWrites=true&w=majority'
    

    but apparently the single quotes shouldn't be there?


  2. You need to call the env load function in the main.go file and also add the mongoDB function in main.go it will work.

    err := godotenv.Load(".env")
    if err != nil {
        log.Fatal("Error loading .env file")
    }
    mongoDbClient := configs.NewNoSqlDB()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search