Skip to content

Instantly share code, notes, and snippets.

@Shivam010
Last active September 13, 2019 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shivam010/bf057e4fcf65954c62751b0e544bbd1e to your computer and use it in GitHub Desktop.
Save Shivam010/bf057e4fcf65954c62751b0e544bbd1e to your computer and use it in GitHub Desktop.
Opening a change stream cursor for any database in go using mongo-go-driver, gives error on cursor decoding.
package main
import (
"context"
"fmt"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo"
"log"
)
const (
config = `mongodb://127.0.0.1:27017`
DB = `testdb`
COL = `col`
)
func errLogs(err error) {
if err != nil {
log.Println(err)
}
}
func traverseCursor(ctx context.Context, cur mongo.Cursor) {
for cur.Next(ctx) {
ele := bson.M{}
err := cur.Decode(&ele)
errLogs(err)
fmt.Println(ele)
}
}
/*
Run this Query:
use testdb;
db.col.insertOne( { name: "Shivam" } );
and the following function (watchOnDB) will panic out with the message:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x58 pc=0x779242]
goroutine 1 [running]:
github.com/mongodb/mongo-go-driver/mongo.(*changeStream).Decode(0xc000118000, 0x7bb880, 0xc000116028, 0xc0000cfe01, 0x42ad92)
$GOPATH/src/github.com/mongodb/mongo-go-driver/mongo/change_stream.go:454 +0x62
main.traverseCursor(0x979100, 0xc00001e0f0, 0x97a0c0, 0xc000118000)
.../main.go:27 +0x48
main.watchOnDB(0x979100, 0xc00001e0f0, 0xc000093400, 0x84e5bc, 0x6)
.../main.go:68 +0x1dc
main.main()
.../main.go:81 +0x119
Process finished with exit code 2
*/
func watchOnDB(ctx context.Context, cli *mongo.Client, _db string) {
fmt.Printf("Starting change stream watch on database %s.\n", _db)
db := cli.Database(_db)
var p interface{}
cur, err := db.Watch(ctx, p)
errLogs(err)
defer cur.Close(ctx)
traverseCursor(ctx, cur)
}
func main() {
ctx := context.Background()
cli, err := mongo.NewClient(config)
errLogs(err)
errLogs(cli.Connect(ctx))
defer cli.Disconnect(ctx)
watchOnDB(ctx, cli, DB)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment