How to update data in mongodb database and show in ui - node.js

Client-side code...!!!
I want to update the quantity by clicking the Delivered button...
In this section have quantity that i'm show bring database.
const [reload, setReload] = useState(true);
const [stock, setStock] = useState({});
const { _id, quantity } = stock;
useEffect(() => {
const url = `http://localhost:5000/stock/${inventoryId}`;
fetch(url)
.then((res) => res.json())
.then((data) => setStock(data));
}, [reload]);
In this function I want to update quantity that i'm decrising by clicking button
const handleDelivered = () => {
const updateQuantity = parseInt(quantity) - 1; // *actually I want to decrise quantity by clicking Delivered button*
const url = `http://localhost:5000/stock/${inventoryId}`;
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify(updateQuantity), // *I don't know it's right or wrong and it's so important*
})
.then((res) => res.json())
.then((data) => {
setReload(!reload);
setStock(data);
console.log(data);
});
};
return <button onClick={handleDelivered}>Delivered</button>
Server-side code...!!!
On server-side I want to update just the quantity value...
app.put('/stock/:id', async (req, res) => {
const id = req.params.id;
const updateQuantity = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
updateQuantity, // *I'm not sure how to set it database. But I want to update quantity value*
},
};
const result = await stockCollection.updateOne(filter, updateDoc, options);
res.send(result);
});

You need to set the updatedQuantity on the "quantity" field of the database. You need to change the "updateDoc" object like this in your server-side code:
const updateDoc = {
$set: {
quantity: updateQuantity,
},
};
Hope this should work.

Client-side code
const handelUpload = (e) => {
e.preventDefault();
const storeQuantity = parseInt(product?.quantity);
const newQuantity = parseInt(e.target.quantity.value);
const quantity = storeQuantity + newQuantity;
if (quantity > 0) {
fetch(`http://localhost:5000/stock/${inventoryId}`, {
method: "PUT",
headers: {
"Content-type": "application/json; charset=UTF-8",
},
body: JSON.stringify({ quantity }),
})
.then((response) => response.json())
.then((data) => {
console.log("success", data);
alert("users added successfully!!!");
e.target.reset();
setIsreload(!isReload);
});
} else {
console.log("input number");
}
};
Server side code api
app.put("/stock/:id", async (req, res) => {
const id = req.params.id;
const updatedProduct = req.body;
console.log(updatedProduct.quantity);
console.log(typeof updatedProduct.quantity);
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updatedDoc = {
$set: {
// name: updatedProduct.name,
// email: updatedProduct.email,
quantity: updatedProduct.quantity,
// price: updatedProduct.price,
},
};
const result = await stockCollection.updateOne(filter,updatedDoc,options
);
res.send(result);
});

Related

How to filter posts by category

I tried to filter posts by category but it's not working on frontend
I want when a user clicks on a particular category to get posts in that category
this is my backend (NODEJS)
exports.getMovies = async (req, res) => {
const { pageNo = 0, limit = 10 } = req.query;
// filter category
let filter = {};
if (req.query.categories) {
filter = { category: req.query.categories.split(",") };
}
const movies = await Movie.find(filter)
.populate("category comments")
.sort({ createdAt: -1 })
.skip(parseInt(pageNo) * parseInt(limit))
.limit(parseInt(limit));
const results = movies.map((movie) => ({
id: movie._id,
title: movie.title,
poster: movie.poster?.url,
responsivePosters: movie.poster?.responsive,
category: movie.category,
comments: movie.comments,
genres: movie.genres,
status: movie.status,
}));
res.json({ movies: results });
};
The front end API
export const getMovies = async (pageNo, limit, filter) => {
const token = getToken();
try {
const { data } = await client(
`/movie/movies?pageNo=${pageNo}&limit=${limit}&filter=${filter}`,
{
headers: {
authorization: "Bearer " + token,
"content-type": "multipart/form-data",
},
}
);
return data;
} catch (error) {
return catchError(error);
}
};
The front end CATEGORY COMPONENT
I want the user to filter the post by category by clicking on the category
export default function AllCategory() {
const [allCategories, setAllCategories] = useState([]);
const fetchCategories = async () => {
const res = await getCategoryForUsers();
setAllCategories(res);
};
useEffect(() => {
fetchCategories();
}, []);
return (
<div className=''>
<ul className=' space-x-4 '>
{allCategories.map((c, index) => {
return <li key={index}>{c.title}</li>;
})}
</ul>
</div>
);
}
Remove the ``` as that is not how to post code here.
You'll want to use a filter first in another function
const [selectedCategories, setCurrentlySelectedCategories] = useState([]);
const handleSelectCategory = (category) => {
const currentlySelected = allCategories.filter((item) => item.category == category);
setCurrentlySelectedCategories(currentlySelected);
}
Now just call map on the selectedCategories

How to update UI after decreasing qtty from backend in react JS?

When I reload the page then quantity is being updated but until page reload quantity does not update on UI. On the other hand, my database decreasing the quantity.
const StockUpdate = () => {
const { id } = useParams();
const [stockUpdate, setStockUpdate] = useState({});
useEffect(() => {
const getItemById = async () => {
const url = `http://localhost:8000/inventory/${id}`
const { data } = await axios.get(url);
setStockUpdate(data);
}
getItemById();
}, [id]);
const handleDeliveryButton = () => {
console.log(stockUpdate)
const item = stockUpdate;
const url = `http://localhost:8000/inventory/${id}`;
fetch(url, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(res => res.json())
.then(data => {
console.log(data)
});
toast('Stock quantity updated after delivery !!!!');
};

How to update product quantity (decrease and restock) from UI and server using MERN?

I want to Decrease product quantity. I want to decrease the quantity when I click the Decrease button, after clicking the button quantity will be decreasing 1 from the server and UI. I write the code, but the problem is when I'm clicking the button, in server site quantity convert as NAN.
* server site code
app.patch("/InventoryItems/:id", async (req, res) => {
const id = req.params.id;
const updatedData = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updatedDoc = {
$set: {
quantity: updatedData.quantity,
},
};
console.log(updatedDoc);
const result = await ServiceCollection.updateOne(
filter,
updatedDoc,
options
);
*clint site code
const handleDelivery = () => {
const newQuantity = parseInt(quantity) + 1;
console.log(newQuantity);
const productQuantity = { newQuantity };
const url = ` http://localhost:5000/InventoryItems/${Id}`;
fetch(url, {
method: "PATCH",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(productQuantity),
})
.then((res) => res.json())
.then((data) => {
setProduct(data);
alert("quantity updatted");
});
};

How to reduce quantity in react.js and node.js

react.js
As you can see in the react code, I am trying to reduce the quantity, but I struggle to do it in react. what I want is if click button then quantity should be reduced 1 by 1. I think I am
const [quantity, setQuantity] = useState(0)
const handleDelivery = event => {
event.preventDefault();
const deliveryInventoryItem = inventoryItem.quantity(quantity-1);
const url = `http://localhost:5000/inventoryItem/${inventoryItemId}`;
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(deliveryInventoryItem)
})
.then(res => res.json())
.then(data => {
console.log('success', data);
alert('users added successfully!');
event.target.reset();
setQuantity(data)
})
}
node.js
app.put('/inventoryItem/:id', async (req, res) => {
const id = req.params.id;
const deliveryInventoryItem = req.body;
console.log(id, updatedInventoryItem);
const filter = {_id: ObjectId(id)};
const options = {upsert: true};
const updatedDoc = {
$set: {
quantity: deliveryInventoryItem.quantity
}
};
const result = await inventoryItemCollection.updateOne(filter, updatedDoc, options);
res.send(result);
})
In mongoDB, use $inc to increase or descrease quantity, see more: MongoDB $inc docs
In React app:
const quantityChange = -1 // If you want decrease 1 by 1 or any number you want increase or decrease by this number
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(quantityChange)
}).then().catch()
...
In Nodejs App, edit your updatedDoc:
const { quantityChange } = res.body
const updatedDoc = {
$inc: {
quantity: quantityChange
}
};

decrease number server making with express put method

I am trying to decrease the quantity, which I have to change on mongodb database, also I need to show it in body. I set a button called delivered which will decrease the quantity value by 1 . but when I click on the delivered button suddenly nodemon index.js cmd crashed. it says"MongoInvalidArgumentError: Update document requires atomic operators"
//Client side:
const handleQuantity = (quantity) => {
const newQuantity = Number(quantity) - 1;
// console.log(newQuantity);
fetch(`http://localhost:5000/inventory/${itemsId}`, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ newQuantity })
})
.then(res => res.json())
.then(data => console.log(data))
}
//server side:
app.put('/inventory/:id', async (req, res) => {
const id = req.params.id;
const property = req.body;
const query = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
quantity: property.newQuantity
}
};
const result = await inventoryCollection.updateOne(query, options, updateDoc);
res.send(result)
})```
Client side:
const handleQuantity = (quantity) => {
const newQuantity = parseInt(quantity) - 1;
// console.log(newQuantity);
fetch(`http://localhost:5000/inventory/${itemsId}`, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ newQuantity })
})
.then(res => res.json())
.then(data => console.log(data))
}

Resources