Lessons

How to Update Data in Mongo with Go

In this tutorial, I will show you the basics of doing a update request to a Mongo database instance with Go code. I will be on local and provide you with all steps.

Setup

I'm assuming you have Mongo installed on your local machine. I also recommend installing Mongo Compass to make it easier to see your data.

I am assuming you have Go installed and have successful compiled at least one Go file. This would confirm your environment works. We will be using my Go boierplate code to save time on setting up our code structure. It follows a handlers, models, repositories, services, and utils structure.

In short:

  • handlers handles the inbound request.
  • models contains all structs that represent data.
  • repositories has all methods for interacting with the database.
  • services contains the business logic of the app.
  • utils has any helper methods.

Download the Go boilerplate. Please give it a star on Github so I know people are still using and enjoying it. Move the files into your new project root. Open the files up in a text editor.

You need to do one thing for this boilerplate to work. Open services/user_service.go and within the IsValidPassword function. You will need to switch the variable to true. Do NOT use this code in production without fixing it. I leave encryption and password requirements up to you. This will store a plain text password till you add code to GetEncryptedPassword and IsValidPassword. For demo and dev purposes, this is fine.

You will need data in your database and checkout the insert tutorial.

Update Code

As you can imagine, we will be working with the repositories layer since it works with the database. If we open the repositories/cars_repository.go file, you can see the Update method.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 func (c *CarsRepository) Update(email string, carID string, body models.UpdateCar) error { docID, err := primitive.ObjectIDFromHex(carID) if err != nil { return err } update := body.Update() if update == nil { return nil } filter := bson.M{"_id": docID, "email": email} _, err = c.db.Collection("cars").UpdateOne(context.TODO(), filter, update) if err != nil { return err } return nil }

In the code above, we covert the ID from a string to an objectID. We then fetch the update settings. This is a function attached to the model object. We will then set up our filter and update one document. In models/Cars.go, you can find type UpdateCar struct.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 type UpdateCar struct { Make string `json:"make"` Model string `json:"model"` Year int `json:"year"` Status string `json:"status"` } func (u *UpdateCar) Valid() error { return nil } func (u *UpdateCar) Update() bson.M { update := bson.M{} if u.Make != "" { update["make"] = u.Make } if u.Model != "" { update["model"] = u.Model } if u.Year != 0 { update["year"] = u.Year } if u.Status != "" { update["status"] = u.Status } if len(update) == 0 { return nil } return bson.M{"$set": update} }

The update method builds a mapping interface to be passed to the Mongo driver.

Demo

In your terminal:

1 go run main.go

The first step is to run sign up or sign in. I execute my sign up request with Postman. Copy down the token in the response.

Screenshot of Github Workflow Running

Or you can run this curl command:

1 2 3 4 5 6 curl --location --request POST 'http://localhost:8080/user/signup/' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "me@keithweaver.ca", "password": "demodemo1" }'

As mentioned, I'm assuming you have data in your database. You will need the ID. Mine is 5f7ef67705b78ca65b721937.

Screenshot of Github Workflow Running

I'm going to update this to be a 1995 Ferrari. I will then update it to be a whole new car.

Screenshot of Github Workflow Running

Or the curl command:

1 2 3 4 5 6 curl --location --request PUT 'http://localhost:8080/cars/5f7ef67705b78ca65b721937' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer 5f7ef37c05b78ca65b721936' \ --data-raw '{ "year": 1995 }'

And the result in the database:

Screenshot of Github Workflow Running

Now, completely changing it. Here is my second request:

Screenshot of Github Workflow Running

Or the curl command:

1 2 3 4 5 6 7 8 9 curl --location --request PUT 'http://localhost:8080/cars/5f7ef67705b78ca65b721937' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer 5f7ef37c05b78ca65b721936' \ --data-raw '{ "year": 2020, "make": "BMW", "model": "X3", "status": "owned" }'

And the result:

Screenshot of Github Workflow Running

That's it. You have now updated a document (twice) in a Mongo database.

Thanks for reading!