inserting multiple data in Mongodb - node.js

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);
});

Related

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 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))
}

Why is react not posting res.json() to console?

I have tried so many thing but my react app is not recieving jsonData variable or res as a return from the node app. The app is working and printing to console on the node side but I can't get it to print onto the react side.
const submitForm = async (event) => {
event.preventDefault(); // Prevent default submission
const data2 = document.getElementById("miles").value;
const data =
"passenger_vehicle-vehicle_type_" +
carType +
"-fuel_source_" +
vehicleType +
"-engine_size_na-vehicle_age_na-vehicle_weight_na";
axios
.post(`http://localhost:8000/api/vehicle/`, { data, data2 })
.then((res) => {
const returnText = res.json();
console.log(returnText);
return res.json();
})
.then((jsonData) => {
console.log(jsonData);
return;
})
.catch((error) => {
console.log("got errr while posting data", error);
});
};
I edited out the api and api key.
var fetch = require('node-fetch');
exports.vehicle = (req, res) =>{
let status;
const { data, data2 } = res.body;
const values = {
"emission_factor": data,
"parameters": {
"distance": parseInt(data2),
"distance_unit": "mi",
},
};
fetch('https://AAAAAAAAAAAAAAAA', {
method: 'POST',
headers: {
'Authorization': 'Bearer MYAPIKEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
.then((res) => {
status = res.status;
return res.json()
})
.then((jsonData) => {
console.log(jsonData);
console.log(status);
return jsonData
})
.catch((err) => {
// handle error
console.error(err);
});
res.send(req.body);
}
Working code thanks for the help:
const submitForm = async (event) => {
event.preventDefault(); // Prevent default submission
const data2 = document.getElementById("miles").value;
const data =
"passenger_vehicle-vehicle_type_" +
carType +
"-fuel_source_" +
vehicleType +
"-engine_size_na-vehicle_age_na-vehicle_weight_na";
axios
.post(`http://localhost:8000/api/vehicle/`, { data, data2 })
.then((res) => {
console.log(res.data);
return;
})
.catch((error) => {
console.log("got err while posting data", error);
});
};
Node solution in comments.
The functions inside your then() statements need to return data e.g. then((res) => {return res.json()})
You have two problems here...
Client-side, you seem to be mixing up an Axios response with a fetch() Response. You want res.data, not res.json(). Since you've tagged this with reactjs, here is where you would set the data to a state value, eg
axios.post(...).then(res => {
setSomeState(res.data)
})
Server-side, you aren't waiting for your fetch request to complete. I'd recommend using an async function
exports.vehicle = async (req, res) => {
try {
const { data, data2 } = req.body
const values = {
"emission_factor": data,
"parameters": {
"distance": parseInt(data2),
"distance_unit": "mi",
},
}
// don't mix up the Express "res" with the fetch "response"
const response = await fetch('https://AAAAAAAAAAAAAAAA', {
method: 'POST',
headers: {
'Authorization': 'Bearer MYAPIKEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
res.json(await response.json()) // respond with the data
} catch (err) {
console.error(err)
res.status(500).send(err)
}
}

NodeJS Axios request returning an odd string

I'm sending a GET request to a third party API and it is returning a odd string (supposed to be an image).
axios.get(`${URL}/test`, {
headers: {
'Content-Type': 'application/json',
},
auth: {
username: USERNAME,
password: PASSWORD
},
responseType: 'blob'
})
.then(async (response) => {
console.log(response.data)
return res.json(response.data);
})
.catch((err) => {
console.log(err);
return res.json("ERROR");
});
The response is:
"����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C
How can I convert it to an image or image/url?
Thanks
You can try this
const Fs = require('fs')
const Path = require('path')
const Axios = require('axios')
async function downloadImage () {
const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true'
const path = Path.resolve(__dirname, 'images', 'code.jpg')
const writer = Fs.createWriteStream(path)
const response = await Axios({
url,
method: 'GET',
responseType: 'stream'
})
response.data.pipe(writer)
return new Promise((resolve, reject) => {
writer.on('finish', () => { /* Add your code here */ resolve(); })
writer.on('error', () => { /* Add your code here */ reject(); })
})
}
downloadImage()

Resources