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))
}
Related
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);
});
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 !!!!');
};
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");
});
};
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
}
};
try to insert multiple data in mongodb but not working
Client site code
const onConfirmOrder = (e) => {
const data = {}
const url = `https://damp-coast-51374.herokuapp.com/product`;
fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(name => {
e.target.reset();
console.log(name);
})
};
this is my server site code
app.post('/invoices', async (req, res) => {
const service = req.body;
const options = { ordered: true };
const result = await invoiceCollection.insertMany(service, options);
res.send(result);
});