// Global variables for db connection , collection and context var db *mongo.Client var blogdb *mongo.Collection var mongoCtx context.Context func main { // STEP 1 & STEP 2 // STEP 3 (gRPC server) // ... // Initialize MongoDb client fmt.Println("Connecting to MongoDB...") // non-nil empty context mongoCtx = context.Background() // Connect takes in a context and options, the connection URI is the only option we pass for now db, err = mongo.Connect(mongoCtx, options.Client().ApplyURI("mongodb://localhost:27017")) // Handle potential errors if err != nil { log.Fatal(err) } // Check whether the connection was succesful by pinging the MongoDB server err = db.Ping(mongoCtx, nil) if err != nil { log.Fatalf("Could not connect to MongoDB: %v\n", err) } else { fmt.Println("Connected to Mongodb") } // Bind our collection to our global variable for use in other methods blogdb = db.Database("mydb").Collection("blog") }