# Failing to insert data - Golang REST API with MongoDB on VSCODE

**URL:** <https://forum.golangbridge.org/t/failing-to-insert-data-golang-rest-api-with-mongodb-on-vscode/31932>\
**Category:** Code Review\
**Created:** [June 13, 2023, 6:18pm UTC](https://forum.golangbridge.org/t/failing-to-insert-data-golang-rest-api-with-mongodb-on-vscode/31932 "2023-06-13T18:18:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shubhra](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/shubhra/32/13485_2.png) [@shubhra](https://forum.golangbridge.org/u/shubhra)\
**Post date:** [June 13, 2023, 6:18pm UTC](https://forum.golangbridge.org/t/failing-to-insert-data-golang-rest-api-with-mongodb-on-vscode/31932/1 "2023-06-13T18:18:44Z")

</div>

Hi Team,

I am trying to run Golang REST API with MongoDB on VSCODE. But, my data is not getting inserted into DB.  
I am new to Golang and RESTAPI and MongoDB. Could you please help me with the below code and let me know why it is not inserting data into MongoDB.

```auto
package main

import (
	"context"

	"encoding/json"

	"fmt"

	"github.com/gorilla/mux"

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

	"go.mongodb.org/mongo-driver/bson/primitive"

	"go.mongodb.org/mongo-driver/mongo"

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

	"net/http"

	"time"
)

var client *mongo.Client

type Person struct {
	ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`

	Firstname string `json:"firstname,omitempty" bson:"firstname,omitempty"`

	Lastname string `json:"lastname,omitempty" bson:"lastname,omitempty"`
}

//func CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {}

//func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {}

//func GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {}

func main() {

	fmt.Println("Starting the application...")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	client, _ = mongo.Connect(ctx, clientOptions)

	router := mux.NewRouter()

	router.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")

	router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")

	router.HandleFunc("/person/{id}", GetPersonEndpoint).Methods("GET")

	http.ListenAndServe("localhost:8080", router)

}

func CreatePersonEndpoint(response http.ResponseWriter,
	request *http.Request) {

	response.Header().Set("content-type", "application/json")

	var person Person

	_ = json.NewDecoder(request.Body).Decode(&person)

	collection := client.Database("books").Collection("person")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	result, _ := collection.InsertOne(ctx, person)

	json.NewEncoder(response).Encode(result)

}

func GetPersonEndpoint(response http.ResponseWriter,
	request *http.Request) {
	response.Header().Set("content-type", "application/json")

	params := mux.Vars(request)

	id, _ := primitive.ObjectIDFromHex(params["id"])

	var person Person

	collection := client.Database("books").Collection("authors")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	err := collection.FindOne(ctx, Person{ID: id}).Decode(&person)

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))

		return

	}

	json.NewEncoder(response).Encode(person)

}

func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {

	response.Header().Set("content-type", "application/json")

	var people []Person

	collection := client.Database("books").Collection("person")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	cursor, err := collection.Find(ctx, bson.M{})

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))

		return

	}

	defer cursor.Close(ctx)

	for cursor.Next(ctx) {

		var person Person

		cursor.Decode(&person)

		people = append(people, person)

	}

	if err := cursor.Err(); err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
		return
	}
	json.NewEncoder(response).Encode(people)

}

```

PS D:\goprojects\gorilla\_mux\_mongodb\> go run main.go  
Starting the application…

```auto
.

```

 ![image](https://forum.golangbridge.org/uploads/default/original/2X/2/214fcda8bb1b24d0336f4718a3c0c6fe482acd44.png)

```auto

```

---

<div class="post-metadata">

**Author:** ![shubhra](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/shubhra/32/13485_2.png) [@shubhra](https://forum.golangbridge.org/u/shubhra)\
**Post date:** [June 13, 2023, 6:20pm UTC](https://forum.golangbridge.org/t/failing-to-insert-data-golang-rest-api-with-mongodb-on-vscode/31932/2 "2023-06-13T18:20:04Z")

</div>

@christophberger Do you see any errors while calling RESTAPI? There is ‘books’ DB and inside it I am trying to create a ‘person’ collection. Somehow data is not getting inserted.
