Commit 5f568797 authored by Chris Morris's avatar Chris Morris
Browse files

Working with MongoDB and Go

parent 6884c5e6
Loading
Loading
Loading
Loading
+45 −0
Original line number Diff line number Diff line
package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"))

	if err != nil {
		log.Fatal(err)
	}
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)
}

// Post is a database type that has a title and a body
type Post struct {
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
}

func InsertPost(title string, body string) {
	post := Post(title, body)
	collection := client.Database("my_database").Collection("posts")
	insertResult, err := collection.InsertOne(context.TODO(), post)

	if err != nil {
		log.Fatal(err)
	}

	fmt.println("Inserted post with ID: ", insertResult.InsertedID)
}

func GetPost(id bson.ObjectID)
+0 −0

File moved.

+2 −1
Original line number Diff line number Diff line
Original API tutorial could be found at https://medium.com/swlh/create-rest-api-in-minutes-with-go-golang-c4a2c6279721
 No newline at end of file
First try tutorial can be found at https://medium.com/swlh/create-rest-api-in-minutes-with-go-golang-c4a2c6279721
First try with database tutorial can be found at https://medium.com/@hugo.bjarred/rest-api-with-golang-mux-mysql-c5915347fa5b