skip to Main Content

I am trying to connect to mongodb from go. My func for getting me the collection

func dbConnection() *mongo.Collection {
    serverAPI := options.ServerAPI(options.ServerAPIVersion1)
    opts := options.Client().ApplyURI("mongodb+srv://username:pwd@domain").SetServerAPIOptions(serverAPI)
    client, err := mongo.Connect(context.TODO(), opts)
    if err != nil {
        panic(err)
    }
    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            panic(err)
        }
    }()
    collection := client.Database("testdb").Collection("test")
    return collection
}

Calling Code:

func sortByName(colls *mongo.Collection) {
    coll := dbConnection()
    filter := bson.D{{Key: "name", Value: "joe"}}
    opts := options.Find().SetSort(bson.D{{Key: "name", Value: 1}})
    cursor, err := coll.Find(context.TODO(), filter, opts)
    if err != nil {
        fmt.Printf("err in FIND: %vn", err)
    }
    var results []bson.D
    err = cursor.All(context.TODO(), &results)
    if err != nil {
        fmt.Printf("err in cursor: %vn", err)
    }
    for _, result := range results {
        fmt.Printf("result: %vn", result)
    }
}

when I am calling this and trying to use the collection I am getting

err in FIND: client is disconnected
panic: runtime error: invalid memory address or nil pointer dereference
    panic: runtime error: invalid memory address or nil pointer dereference
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x48 pc=0xcb7b33b]


Any help appreciated.

2

Answers


  1. In your code

        defer func() {
            if err = client.Disconnect(context.TODO()); err != nil {
                panic(err)
            }
        }()
    

    this will call after the code reaches end of dbConnection function.
    so it will disconnect from mongodb.

    Login or Signup to reply.
  2. to fix this, manage the MongoDB client’s lifecycle at a higher level in your application. Connect to the MongoDB client when the program starts and disconnect when it finishes.

        var client *mongo.Client
    
    func init() {
        var err error
        opts := options.Client().ApplyURI("mongodb+srv://username:pwd@domain")
        client, err = mongo.Connect(context.TODO(), opts)
        if err != nil {
            panic(err)
        }
    }
    
    func dbConnection() *mongo.Collection {
        return client.Database("testdb").Collection("test")
    }
    
    func sortByName() {
        coll := dbConnection()
        filter := bson.D{{Key: "name", Value: "joe"}}
        opts := options.Find().SetSort(bson.D{{Key: "name", Value: 1}})
        cursor, err := coll.Find(context.TODO(), filter, opts)
        if err != nil {
            fmt.Printf("err in FIND: %vn", err)
        }
        var results []bson.D
        err = cursor.All(context.TODO(), &results)
        if err != nil {
            fmt.Printf("err in cursor: %vn", err)
        }
        for _, result := range results {
            fmt.Printf("result: %vn", result)
        }
    }
    
    func main() {
        defer func() {
            if err := client.Disconnect(context.TODO()); err != nil {
                panic(err)
            }
        }()
        sortByName()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search