#MongoDB FindOne

34 messages · Page 1 of 1 (latest)

astral cobalt
#

I can successfully test that I can create a client for a new MongoDB connection

verbal bloom
#

what error are you getting from the fetchdoc function?

astral cobalt
#

here is the doc schema:

astral cobalt
verbal bloom
#

print the error instead and see what it actually says

#

panic is not really for error handling anyway

astral cobalt
#

oh ok one sec

#

that's just a fmt.Println(err) correct?

verbal bloom
#

yup

astral cobalt
#

hmmm...says "client is disconnected"

#

is there something I should be doing when creatign the mongo client first and then passing that into another function?

verbal bloom
#

I think the defer that you have there is disconnecting the client

astral cobalt
#

ok lemme try again

#

maybe I need to take that line out in my mongoclient func?

#

here's my new InitMongoClient function:

    uri := "mongodb+srv://<username>:<password>@cluster0.ifbxo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"

    client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))

    if err != nil {
        panic(err)
    }
    return client
#

and it returned nothing back to me

verbal bloom
#

instead of panicing in the db init function you could return (*Client, error) and handle error in your main function

astral cobalt
#

how do you return 2 things in a function?

verbal bloom
#

idk if you have to set serverAPI explicitly for the connection, although I am not a mongodb enjoyer

#

return client, nil on success

#

or return nil, err in your case

#

and

func InitMongoClient() *mongo.Client

should be

func InitMongoClient() (*mongo.Client, error)

astral cobalt
#

ok leme try

#

it doesn't look like anything is wrong with it:

#
    mongoClient, err := InitMongoClient()
    fmt.Printf("%v and %v", mongoClient, err)
#

do I need to use the UseSession function on the mongo Client?

verbal bloom
#

you have to check the error and go on from there

#

if err != nil { ... }

#

but yeah the error seems empty so the problem is somewhere else

astral cobalt
#

problem is that nothing is being returned back to me when I print the error, but it's not returning any mongo data back from me as well

buoyant sky
#

Note this part of your code```go
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()

#

deferred functions are called when the function surrounding it returns (so in this case InitMongoClient)