Skip to content

Commit 3949b7e

Browse files
committed
added express examples to CRUD reqs
1 parent 0292a68 commit 3949b7e

File tree

1 file changed

+102
-13
lines changed
  • module3-crud-and-data-models/r1-schema-and-data-models

1 file changed

+102
-13
lines changed

module3-crud-and-data-models/r1-schema-and-data-models/README.md

Lines changed: 102 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ module.exports = mongoose.model("customer", customer);
2323
The same `customer` schema in PostgreSQL database using sequelize.
2424

2525
```js
26+
const Sequelize = require("sequelize");
27+
2628
module.exports = (sequelize, DataTypes) => {
2729
const Customer = sequelize.define("customer", {
2830
name: {
@@ -43,20 +45,31 @@ We can see that the schema definition for the `customer` has a `name` that is ty
4345

4446
When we are building APIs, we want our models to provide four basic types of functionality. The model must be able to Create, Read, Update, and Delete resources. Computer scientists often refer to these functions by the acronym CRUD. A model should have the ability to perform at most these four functions in order to be complete.
4547

46-
### CRUD and REST
48+
### CRUD in REST
4749

48-
**What is REST?**
50+
In a REST environment, CRUD often corresponds to the [HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) `POST`, `GET`, `PUT`, and `DELETE`, respectively. These are the fundamental elements of a persistent storage system.
4951

50-
REST is a set of architectural constraints. API developers can implement REST in a variety of ways. When a client request is made via a RESTful API, it transfers data as an object in some format to the requester or endpoint. There are several formats, JSON is the most generally popular file format to use.
52+
For example, imagine we are working with a system that is keeping track of meals and their corresponding prices for a restaurant. Let’s look at how we would implement CRUD operations.
5153

52-
**Resource in REST**
53-
A resource in REST is a like an Object or an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the decided on format and client can understand the same format. A resource can be any information that can be named (e.g. a person, a user, an invoice, a collection of invoices, etc).
54+
First of all, we need to define our food item schema (we will use mongoose for that), and let's call it "dish".
5455

55-
### CRUD (CREATE, READ, UPDATE, DELETE)
56+
```js
57+
const mongoose = require("mongoose");
5658

57-
In a REST environment, CRUD often corresponds to the [HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) `POST`, `GET`, `PUT`, and `DELETE`, respectively. These are the fundamental elements of a persistent storage system.
59+
const dish = new mongoose.Schema({
60+
title: {
61+
type: String,
62+
required: true,
63+
},
64+
image: {
65+
type: String,
66+
required: true,
67+
},
68+
tags: [String],
69+
});
5870

59-
For example, imagine we are working with a system that is keeping track of meals and their corresponding prices for a restaurant. Let’s look at how we would implement CRUD operations.
71+
module.exports = mongoose.model("dish", dish);
72+
```
6073

6174
#### Create
6275

@@ -65,11 +78,11 @@ Imagine that we are adding a new food item to the stored list of dishes for this
6578

6679
Note: Use `POST` when you want to add a child resource under resources collection.
6780

68-
##### Request:
81+
Request:
6982

7083
`POST http://www.myrestaurant.com/api/dishes/`
7184

72-
We will need to send the dish data too as an object.
85+
We will need to send the dish data too as an object in the body.
7386

7487
For example
7588

@@ -79,6 +92,26 @@ For example
7992
image: "www.food.com/lasagna.jpg",
8093
tags: ["simple", "classic"]
8194
}
95+
96+
```
97+
98+
On the backend side, our express route will be
99+
100+
```js
101+
router.post("/dishes", async (req, res) => {
102+
// get the data we sent in the body
103+
const dishData = req.body;
104+
try {
105+
// using the create() method with Mongoose will insert the data we sent in the body to our MongoDB database
106+
// and return an object of that data when done
107+
const newDish = await DishModel.create(dishData);
108+
// then, we return the new created dish object
109+
res.status(201).json(newDish);
110+
} catch (err) {
111+
res.status(422).json({ message: err.message });
112+
}
113+
});
114+
})
82115
```
83116

84117
#### Read
@@ -87,18 +120,29 @@ To read resources in a REST environment, we use the GET method. In practice, rea
87120

88121
To read resources in a REST environment, we use the GET method. Reading a resource should never change any information - it should only retrieve it. REST itself is more like a set of guidelines. Technically, you can change data in a `GET` request, but since we are creating a RESTful API, you shouldn't do that. Having a GET request that updates data in your database would be confusing to the users of your API and violate the expected behavior of REST.
89122

90-
##### Request:
123+
Request:
91124

92125
`GET http://www.myrestaurant.com/api/dishes/`
93126

127+
The express route for getting all dished will be
128+
129+
```js
130+
router.get("/dishes", async (_, res) => {
131+
// here, we are using the find() to return all dishes from our MongoDB database
132+
// find() will return an array of dish objects
133+
const posts = await DishModel.find();
134+
res.json(posts);
135+
});
136+
```
137+
94138
#### Update
95139

96140
PUT is the HTTP method used for the CRUD operation, Update.
97141
So if the price of Avocado Toast has gone up, we should go into the database and update that information using PUT.
98142

99143
Note: Use `PUT` when you want to modify a singular resource which is already a part of resources collection. `PUT` replaces the resource with the data you send in its entirety.
100144

101-
##### Request:
145+
Request:
102146

103147
`PUT http://www.myrestaurant.com/dishes/:id`
104148

@@ -114,15 +158,60 @@ For example
114158
}
115159
```
116160

161+
Note that when using Mongoose you don't have to send all the object fields, you can only send the ones that got changed.
162+
163+
For example, we can only send the title.
164+
165+
```js
166+
{
167+
title: "New dish title",
168+
}
169+
```
170+
171+
Respectively, our express route for both these examples will be
172+
173+
```js
174+
router.put("/dishes/:id", async (req, res) => {
175+
// we need the dish id in order to tell Mongoose which dish to update in our database
176+
const { id } = req.params;
177+
try {
178+
// the findByIdAndUpdate() will make sure the dish exist before updating it
179+
const updatedDish = await DishModel.findByIdAndUpdate(id, req.body, {
180+
// the { new: true } here is just to tell Mongoose we want the newely updated dish back
181+
new: true,
182+
});
183+
// we return the updated dish as a JSON object to the user
184+
res.json(updatedDish);
185+
} catch (err) {
186+
res.status(422).json({ message: err.message });
187+
}
188+
});
189+
```
190+
117191
#### Delete
118192

119193
The CRUD operation Delete corresponds to the HTTP method DELETE. It is used to remove a resource from the system.
120194
Let’s say that the world avocado shortage has reached a critical point, and we can no longer afford to serve this modern delicacy at all. We should go into the database and delete the item that corresponds to **Avocado Toast**, which we know has an `id` of 1223.
121195

122-
##### Request:
196+
Request:
123197

124198
`DELETE http://www.myrestaurant.com/dishes/:id`
125199

200+
The express route for this deleting request can be
201+
202+
```js
203+
router.delete("/dishes/:id", async (req, res) => {
204+
const { id } = req.params;
205+
try {
206+
const dish = await PostModel.findByIdAndDelete(id);
207+
// the status code is 204 because we are not returning data or entities
208+
return res.status(204).json({ success: true });
209+
} catch (err) {
210+
res.status(422).json({ message: err.message });
211+
}
212+
});
213+
```
214+
126215
## Resources
127216

128217
- [What is REST](https://restfulapi.net/)

0 commit comments

Comments
 (0)