recipes/mongodb

MongoDB

Connecting to a MongoDB database.

MongoDB Example

Github StackBlitz

This project demonstrates how to connect to a MongoDB database in a Go application using the Fiber framework.

Prerequisites

Ensure you have the following installed:

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/mongodb
  2. Install dependencies:

    go get
  3. Start MongoDB using Docker:

    docker compose up -d
  4. (Optional) Set the MONGO_URI environment variable. Defaults to mongodb://localhost:27017/fiber_test:

    export MONGO_URI="mongodb://localhost:27017/fiber_test"

Running the Application

  1. Start the application:
    go run main.go

Endpoints

The application is a small employee API over the employees collection of the fiber_test database. id is the MongoDB ObjectID, as a hex string.

MethodURLDescriptionSuccess
GET/employeeLists all employees200
GET/employee/:idGets an employee by ID200
POST/employeeCreates an employee201
PUT/employee/:idUpdates an employee200
DELETE/employee/:idDeletes an employee204

An invalid :id answers 400, and an unknown one 404.

Example Requests

Create an Employee

curl -X POST http://localhost:3000/employee \
  -H "Content-Type: application/json" \
  -d '{"name": "Jane Doe", "salary": 52000, "age": 31}'

List Employees

curl http://localhost:3000/employee

Get, Update and Delete an Employee

Use the id returned when you created the employee:

curl http://localhost:3000/employee/<id>

curl -X PUT http://localhost:3000/employee/<id> \
  -H "Content-Type: application/json" \
  -d '{"name": "Jane Doe", "salary": 56000, "age": 32}'

curl -X DELETE http://localhost:3000/employee/<id>

References