Last active
December 24, 2020 22:06
-
-
Save sedataktas/68c49a107fa2a034411d91bef5bf1aab to your computer and use it in GitHub Desktop.
MongoDB conenction
This file contains hidden or 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
| import ( | |
| "context" | |
| "go.mongodb.org/mongo-driver/mongo" | |
| "go.mongodb.org/mongo-driver/mongo/options" | |
| "log" | |
| ) | |
| var ( | |
| BooksCollection *mongo.Collection | |
| AuthorsCollection *mongo.Collection | |
| Ctx = context.TODO() | |
| ) | |
| /*Setup opens a database connection to mongodb*/ | |
| func Setup() { | |
| host := "127.0.0.1" | |
| port := "27017" | |
| connectionURI := "mongodb://" + host + ":" + port + "/" | |
| clientOptions := options.Client().ApplyURI(connectionURI) | |
| client, err := mongo.Connect(Ctx, clientOptions) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| err = client.Ping(Ctx, nil) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| db := client.Database("example") | |
| BooksCollection = db.Collection("books") | |
| AuthorsCollection = db.Collection("authors") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment