This project helps you build a basic CRUD application using Mongoose, Express, and MongoDB. You'll learn to:
- Create and manage a MongoDB database.
- Use Mongoose to define schemas and interact with the database.
- Develop RESTful API routes for CRUD operations.
- Test API routes using Postman and explore them through a minimal front-end.
- CRUD Operations:
- Create: Add plants to the database.
- Read: Fetch plant details.
- Update: Modify plant attributes.
- Delete: Remove plants from the database.
- Mongoose Schema:
- Enforces structure on plant data with validation and constraints.
- Error Handling:
- Gracefully handles issues like duplicates or missing fields.
- Initial Database Load:
- Loads your database with 10 starter documents.
├── controllers
│ └── PlantController.js # CRUD logic and middleware
├── models
│ └── PlantModel.js # Defines the schema for plants
├── routes
│ └── plantRoutes.js # Routes and their corresponding controller methods
├── public
│ └── index.html # Minimal UI for interacting with the API
├── main.js # Entry point for the application
├── .env # Environment variables (MongoDB URI) - must be created by the user, used by the `dotenv` library
├── package.json # Dependencies and scripts
└── README.md # Documentation
- Node.js (v14+ recommended)
- MongoDB (local or cloud-based instance)
-
Fork and clone the repository:
git clone <repo-url> cd mongoose_demo
-
Install dependencies:
npm install
-
Set up a MongoDB database (see the section below for details).
-
Create a
.env
file in the project root:MONGO_URI=<your-mongo-db-uri>
-
Start the server:
npm start
The server runs on http://localhost:3000. The front-end is served at the root route.
-
Go to MongoDB Atlas and create a free account.
-
Create a cluster:
- Choose your cloud provider and region.
- Click "Create Cluster."
-
Configure a database user:
- Go to Database Access and click "Add New Database User."
- Set a username and password. Copy the password for later.
-
Whitelist your IP:
- Go to Network Access and click "Add IP Address."
- Add your current IP or allow access from anywhere with
0.0.0.0/0
.
-
Get your connection string:
- Go to Clusters and click "Connect."
- Choose Connect your application and copy the connection string.
-
Update your
.env
file: Replace<password>
with your database user's password and<database-name>
with the name of your database:MONGO_URI=mongodb+srv://<username>:<password>@<cluster-url>/<database-name>?retryWrites=true&w=majority
Important: Pay special attention to
<database-name>
. If you don't specify a database name here, MongoDB will create a default database called "test" and store your collection in it. It's a good practice to explicitly name your database to keep your collections organized and easy to identify. -
Alternatively, replace the argument of
mongoose.connect
inmain.js
with your connection string. Uploading this to GitHub is a security risk.
mongodb+srv
: Indicates the use of the SRV protocol.<username>
and<password>
: Your database credentials.<cluster-url>
: The cluster's unique URL.<database-name>
: The database name where your collections will be stored.- Query parameters like
retryWrites=true
configure connection behavior.
-
Download and install MongoDB Community Server.
-
Start the MongoDB server:
mongod
-
Use this connection string in your
.env
file:MONGO_URI=mongodb://localhost:27017/<database-name>
-
Alternatively, replace the argument of
mongoose.connect
inmain.js
with your connection string.
Use Postman to test the following endpoints:
-
Create a Plant
POST/plants
Body:{ "name": "POMEGRANATE", "type": "Fruit", "price": 30 }
-
Read a Plant
GET/plants/:name
plants/ROSE
-
Update a Plant
PATCH/plants/:name
Body:{ "price": 20 }
-
Delete a Plant
DELETE/plants/:name
plants/ROSE
Open index.html
in your browser by going to the root route at http://localhost:3000 to interact with the API. Use the forms provided to make requests and view responses.
- Learn how to:
- Define Mongoose schemas and models.
- Create middleware for CRUD operations.
- Build RESTful API routes in Express.
- Test APIs with Postman.
- Explore error handling and debugging techniques.
- Understand the flow of data between the front end, back end, and database.
File: models/PlantModel.js
Defines a Plant
schema with name
, type
, and price
, and family
fields. The name
field has a unique constraint to prevent duplicates. The family
field is optional.
File: controllers/PlantController.js
Implements:
createPlant
: Adds a new plant.getPlant
: Retrieves a plant by name.updatePlant
: Updates a plant's details.deletePlant
: Removes a plant.loadInitialPlants
: Preloads the database with predefined plants.
File: routes/plantRoutes.js
Defines the API endpoints and links them to controller methods.
-
Focus on API Testing:
- Use Postman or cURL to send requests and inspect responses.
- Experiment with different inputs to understand how the API behaves.
-
Understand Mongoose Queries:
- Refer to the Mongoose documentation to learn more about methods like
create
,findOne
,findOneAndUpdate
, etc.
- Refer to the Mongoose documentation to learn more about methods like
-
Debugging:
- Use
console.log
in the controller and model files to trace the flow of data.
- Use
-
Handling Errors:
- Observe how errors (e.g., duplicate keys, missing fields) are managed in the
PlantController
. - To explore the global error handler, uncomment the line throw new Error('This is my custom error I made up'); in the getPlant method. This triggers a Node.js error object and demonstrates how the application responds to unexpected errors.
- Observe how errors (e.g., duplicate keys, missing fields) are managed in the
Feel free to modify the code and experiment to solidify your understanding of Express and Mongoose!