Creating a REST API for an Ice Cream Company with MongoDB
Written on
Chapter 1: Introduction to Express and MongoDB
In this guide, we will create an API for our ice cream business utilizing MongoDB and Express.js.
What is Express?
Express.js is a robust web application framework for Node.js.
What is MongoDB?
MongoDB is a scalable, cloud-based NoSQL document database.
Initializing Our Project
First, we will create a folder for our project named icecream-api and navigate into it.
$ mkdir icecream-api
$ cd icecream-api
Next, we will initialize a package.json file to manage our project dependencies using yarn.
$ yarn init --yes
Now, let’s install our required dependencies:
$ yarn add express cors mongoose @mongoosejs/double dotenv
We will also install nodemon as a development dependency.
$ yarn add nodemon --dev
Your package.json file should resemble the following:
{
"name": "icecream-api",
"version": "1.0.0",
"main": "server.js",
"license": "MIT",
"dependencies": {
"@mongoosejs/double": "^0.2.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"mongoose": "^6.4.3"
},
"devDependencies": {
"nodemon": "^2.0.19"},
"scripts": {
"start": "nodemon server.js"}
}
Creating a MongoDB Cluster
To set up a MongoDB cluster, log in or sign up for MongoDB and navigate to the 'Database deployment' page.
- Click the 'Create' button.
- Choose 'Shared' for a free cluster option.
- Select your preferred cloud provider and region (e.g., AWS, N. Virginia).
- Name your cluster icecream-db and create it.
Database Access
Under the Security section, click on 'Database access' and then 'Add New Database User'. Set the authentication method to 'Password', create a username and password, and assign the 'Atlas Admin' role.
Network Access
In the Security section, go to 'Network access' and click 'Add IP Address'. Allow access from anywhere.
Now, let’s connect our application to this cluster!
Creating a .env File
Create a .env file in your project folder to store environment variables.
PORT=5000
MONGO_URL=mongodb+srv://<username>:<password>@cluster0.example.mongodb.net/?retryWrites=true&w=majority
Replace <username> and <password> with the credentials you created.
Connecting to MongoDB
Create a file named mongo.js in our project directory and add the following code:
const mongoose = require("mongoose");
const Double = require('@mongoosejs/double');
require("dotenv").config();
const PORT = process.env.PORT;
const MONGO_URL = process.env.MONGO_URL;
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', err => console.log(err));
async function startServer(app) {
await mongoose.connect(MONGO_URL);
app.listen(PORT, () => {
console.log(Server is listening on port ${PORT}!);});
};
module.exports = {
startServer
};
Initializing the Express Server
Create a server.js file in your project. We will include the following dependencies:
const express = require("express");
const cors = require("cors");
require("dotenv").config();
const {startServer} = require("./mongo.js");
const app = express();
app.use(express.json());
app.use(cors());
startServer(app);
Creating Mongoose Schema & Model
In mongo.js, create a schema called icecreamSchema to define the properties:
const Schema = mongoose.Schema;
const icecreamSchema = new Schema({
flavour: {
type : String,
required: true
},
price : {
type : Schema.Types.Double,
required: true
}
});
const Icecream = mongoose.model("Icecream", icecreamSchema);
module.exports = {
startServer,
Icecream
};
Creating Server Routes
We will add routes to our API in server.js.
POST Route: Adding Ice Creams
app.post("/add-icecream", async(req, res) => {
try {
const response = await Icecream.create(req.body);
res.json(response);
} catch(error) {
res.json({message : error});}
});
GET Route: Retrieving Ice Creams
app.get("/ice-creams", async (req, res) => {
try {
const response = await Icecream.find();
res.json(response);
} catch (error) {
res.json({message : error});}
});
DELETE Route: Removing Ice Creams
app.delete("/remove-icecream/:id", async(req, res) => {
try {
const response = await Icecream.findByIdAndDelete(req.params.id);
res.json(response);
} catch (err) {
res.json({message: err});}
});
PATCH Route: Updating Ice Creams
app.patch("/edit-icecream/:id", async (req, res) => {
try {
const response = await Icecream.updateOne({_id : req.params.id}, {$set : req.body});
res.json(response);
} catch(err) {
res.json({message : err});}
});
Now that we have our API set up, let's learn more about MongoDB.
This video titled "Learn MongoDB in 1 Hour" provides a comprehensive overview of MongoDB for beginners.
Chapter 2: Advanced MongoDB Techniques
For those wanting to dive deeper, check out the full course linked below.
This "MongoDB Tutorial for Beginners" offers an extensive look at MongoDB functionalities and usage.