recipes/mongodb
MongoDB
Connecting to a MongoDB database.
MongoDB Example
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:
- Golang
- Fiber package
- MongoDB
- MongoDB Go Driver
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/mongodbInstall dependencies:
go getStart MongoDB using Docker:
docker compose up -d(Optional) Set the
MONGO_URIenvironment variable. Defaults tomongodb://localhost:27017/fiber_test:export MONGO_URI="mongodb://localhost:27017/fiber_test"
Running the Application
- 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.
| Method | URL | Description | Success |
|---|---|---|---|
| GET | /employee | Lists all employees | 200 |
| GET | /employee/:id | Gets an employee by ID | 200 |
| POST | /employee | Creates an employee | 201 |
| PUT | /employee/:id | Updates an employee | 200 |
| DELETE | /employee/:id | Deletes an employee | 204 |
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/employeeGet, 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>