Created
May 8, 2019 12:06
-
-
Save kyriediculous/6b82c26d419a2ff72f5b96713c06c18b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment