I am trying to fetch data from one MongoDB collection and with that result, I am passing that value into another function to get the data from GridFS files for same id.
router.get('/employee/:id', async(req,res) =>{
let gID = req.params.id;
var getUser = await User.find({id:gID});
//console.log(res);
console.log(getUser);
if(getUser){
try{
gfs.files.find({objectID:getUser.id}).toArray(async (err, files) => {
if (!files || files.length === 0) {
res.send({
message: "No User Found",
});
} else {
res.send({
message: "data fetched",
data: getUser,
image: files
});
}
});
}catch(err){
res.send({
message:err.code,
data:err
});
}
}else{
res.send({
message:"error in getting the data",
});
}
})
I tried of this but I am not able to get the expected result, I am getting the user information from getUser but I am not able to fetch the file tagged with that user from GridFS. Can anyone tell me where I am lagging and how could I correct this.
Related
I am working on a React App, and i'm trying to get some data using an axios GET request from my node backend.
the Api Endpoint i'm currently using that regard this problem is the following:
// NodeJS Backend
app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { // GET - Company by User UUID
const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)';
connection.query(selectQuery, [req.params.user_uuid], (err, results) => {
if(err) {
res.send(err)
} else if (results.length === 0) {
res.json({status: 404, message: 'Company not found'})
} else {
res.json({data: results})
}
});
});
This is my Front End:
// ReactJS FrontEnd
const companyLogo = userCompany ? userCompany.logo_url : null;
console.log(userCompany);
useEffect(() => {
const getUserCompany = async () => {
try {
await axios.get(process.env.REACT_APP_API_URL + 'companys/user/' + userUuid).then((response) => {
console.log("response "+ response);
let res = response.data.data[0];
console.log(res);
setUserCompany(res);
});
} catch (error) {
console.log(error);
}
};
getUserCompany();
}, [userUuid]);
There app works fine, but on the console the following error appear:
The object below the error is in fact the thing that i need (companyLogo)
I was wondering if someone know what am I doing wrong on my frontend to fix the TypeError.
Thanks for the help!
If you use optional chaining (?.) to catch possible null/undefined values, you'll most likely fix the issue.
So like this: let res = response.data.data?.[0];
I am uploading the excel sheet in DB with the help of Nodejs, I am unable to authenticate and return the error as already exists the userid when the item.USER_ID already exists in DB. my server goes crashes and returns an error as Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Please help in the code how I fix this issue and make it, If the item.USER_ID already exists return error else insert.
var XLSX = require("xlsx");
const fs = require("fs");
try {
const transaction = await con.transaction();
var workbook = XLSX.readFile("myfile.xlsx");
let json_data = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1);
let count = 0;
json_data.map(async (item) => {
let stmt1 = await con.query("SELECT * FROM `table` WHERE `user_id` = :userid", { replacements: { userid: item.USER_ID }, type: con.QueryTypes.SELECT });
if (stmt1.length > 0) {
await transaction.rollback();
return res.json({ message: "already exist the userid" });
} else {
let stmt2 = await con.query("INSERT INTO `table` (`user_id` , `user_name`) VALUES ( :user_id , :user_name)", {
replacements: {
user_id: item.USER_ID,
user_name: item.USER_NAME,
},
type: con.QueryTypes.INSERT,
transaction: transaction,
});
count++;
if (count == json_data.length) {
await transaction.commit();
return res.json({ message: "file uploaded successfully.." });
}
}
});
} catch (err) {
await transaction.rollback();
return res.json({ code: 500, message: { msg: "SQL ERROR" }, error: err.stack, status: "error" });
}
Here in your code, you are calling the res.json({ message: "file uploaded successfully.." }) inside json_data.map function.
since you are calling the res.json function inside an array, it'll be called as many times as of elements present in the array and as we know, we can sent only 1 response at a time for a request.
Because of which you're catching the errors Cannot set headers after they are sent to the client
just remove that res.json inside the map function, add it at the last of that particular map function.
I know you might question for the condition count == json_data.length you added to the code but javascript is async and this particular block can be executed before to that.
Hope this answer helps you! Please comment if you get any errors or have questions.
I'm trying to update data from ui but data does not update though it can be done using postman and in payload data is also being passed.
Here is handle submit function:
enter code here
data.append("thingsTodo", values.thingsTodo);
data.append("minDaysToSpent", values.minDaysToSpent);
data.append("usp", values.usp);
data.append("geoRegion", values.geoRegion.value);
data.append("altitude", values.altitude);
data.append("thingsToConsider", values.thingsToConsider);
try {
const response = await axios.put(`/api/place/${id}`, data).then((data)=>console.log(data,"data"));
controller:
exports.updatePlace = async (req,res) => {
try {
let place = Place.findById(req.params.id)
if(!place){
return res.status(404).json({success:false,message:"Place does not exists"})
}
console.log(req.body)
place = await Place.findByIdAndUpdate(req.params.id,req.body,{new:true})
res.status(200).json({
success:true,
message:"Place Updated Successfully",
place
})
} catch (error) {
return res.status(500).json({
success:false,
error:error.message
})
}
}
While trying to fetch data from my express backend and MySQL database, with my react frontend using axios, it fails to set the fetched data using useState
my frontend function looks like this
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
});
};
and my backend function looks like this
const searchUser = (req, res) => {
const keyword = req.body.username;
db.query(
"SELECT id,username FROM users WHERE username like ?",
"%" + keyword + "%",
(err, result) => {
if (err) {
res.json({ message: err });
console.log(err);
} else {
console.log(result);
res.json({ result });
}
}
);
};
I tried many methods while saving the data with the useState hook, I appreciate any help
While using Promises and then instead of async / await make sure to catch the errors if your fetch fails.
Unless you share with us the whole component that contains the searchUser function and how you defined the state i cannot pin point you on the error.
What i suggest you to do is adding a catch to your fetch by doing the following:
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
}).catch((error) => {
console.error(error);
});
};
If any abnormalities has happened in your request the catch will tell you! Don't underestimate it's power.
Another path you can look into is console logging your output in front end searchUser function just before setting it in the state.
I did solve the problem, just by replacing res.json({ result }); to res.json(result); in the last line in my backend function
I have read all sorts of variations of this on stackoverflow but I cannot seem to find a post that exactly explains what I'm trying to achieve, at the same time I believe this has to be a very common task during saving data.
So I need to save data to one collection and then read the _id from that doc and save it to a doc in a different collection. I have the following code and I can see the correct data with console.log but I don't see the data being saved to the database.
Appreciate if someone can guide me in the right direction.
Thank you!
router.post('/signup', async (req, res) => {
const { email, password, name, country } = req.body;
try {
const user = new User({ email, password });
await user.save((error, doc) => {
if (error) {
console.log(error);
} else {
const userProfile = new UserProfile({ userId: doc._id, name, country });
userProfile.save((error, doc) => {
if (error) {
console.log(error)
} else {
console.log(doc) // Can see this log with the correct data
}
});
}
});
const token = jwt.sign({userId: user._id}, 'MY_KEY');
res.send({ token });
} catch(error) {
return res.status(422).send(error.message)
}
})