CRUD:
Most important thing in backend development.
CRUD means C for Create/POST, R for Read/GET, U for Update/Patch and D for Delete
I will try to describe these operations with some examples. How do we make this using ReactJs and NodeJs very simply.
POST/CREATE:
In a very simple way CREATE means client will give some input data then it will take to the backend side or server side then it will save into the database.
User will give input form data and submit it with a url called.
fetch('http://localhost:5000/add-users', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(newUser)
})
From the client side data will pass into the backend and it will save into database in a specific collection.
app.post('/add-users', async (req, res) => {
const newUser = req.body // receive data from frontend
const result = await usersCollection.insertOne(newUser); // save data to the database
/>
res.send(result); // send response to the frontend.
});
After that a successful response will go from the backend side to the client side.
User will see a success message
.then(res => res.json())
.then(data => {
if (data.insertedId) {
alert('Successfully added the user.')
e.target.reset();
}})
READ/GET:
Get the data from the database and show it to the client side.
When we want to show some data to the client side and the page is loaded then it will call the API url for getting the data.
fetch(`http://localhost:5000/users`)
app.get('/users', async (req, res) => {
const cursor = usersCollection.find({});
const users = await cursor.toArray();
});
Server side receive the data from the database and send it to the client side.
res.send(users);
From client side data will show to the UI
- .then(res => res.json())
.then(data => {
setUsers(data.users)
});
user.map(.............)
UPDATE/PUT:
Updating and existing data from the database. Sometimes we need to edit our existing data. In that we make a method for updating data.
Itβs one kind of POST method. User will give some data from the client side and hit a url then it will come to the backend side and from the backend side they will check in to the database if the condition matches then data will update into the database and after that it will send a successful response to the client side.
const url = `http://localhost:5000/update-user/${userId}`;
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(user)
})
We need to pass the unique data to sure that which object data we want to change.
app.put('/update-user/:id', async (req, res) => {
const id = req.params.id;
console.log('updating', id)
const updatedUser = req.body;
const filter = { _id: ObjectId(id) }; // filtering user's object
const options = { upsert: true }; // update and insert
const updateDoc = { // set data
$set: {
fname: updatedUser.fname,
lname: updatedUser.lname,
address: updatedUser.address,
email: updatedUser.email
},
};
const result = await usersCollection.updateOne(filter, updateDoc, options) // updating res.json(result) // send response to frontend
Updated data from database
Response send from backend to the client side.
res.json(result) // send response to frontend
.then(res => res.json())
.then(data => {
if (data.modifiedCount > 0) {
alert('Update Successful');
setUser({});
e.target.reset();
}
})
DELETE:
Delete existing data
I click a specific button to delete the data. After that the delete API url hit and the backend received the unique value to identify which data we want to delete.
<button onClick={() => handleDeleteUser(user._id)} className="btn btn-danger" >delete</button>
- const handleDeleteUser = id => {
const proceed = window.confirm('Are you sure, you want to delete?');
if (proceed) {
const url = `http://localhost:5000/users/${id}`;
fetch(url, {
method: 'DELETE'
})
Backend receives the unique value(id) and makes a query to find out the specific data for delete.
app.delete('/users/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
}
Data will be deleted from the database.
- res.json(result);
Send a success message to the client.
- .then(res => res.json())
.then(data => {
if (data.deletedCount > 0) {
alert('deleted successfully');
}
Top comments (0)