mongoose how to update an user profile with id - javascript

I created an simple CRUD operation in nodejs and mongoose. Updating an user using RESTAPI.
an error message in Insomnia
Error: Server returned nothing (no headers, no data)
URL
http://localhost:1337/api/users/update/63ab9b716065482273e58b75
#PUT METHOD
router.put("/update/:id",updateUser)
const updateUser = async (req,res,next) => {
if (req.params.id === req.user.id) {
try {
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set:req.body,
})
res.status(200).json(updateuser)
} catch (error) {
next(error)
}
}
}
how to updating with id of user

req.params.id will be of type string, while req.user.id will be probably of type ObjectId.
Can you try this:
if (req.params.id.toString() === req.user.id.toString()) {

As mentioned before req.user.id type is ObjectId. Also you should send an error when ids are not the same.
Example for your code:
const updateUser = async (req, res, next) => {
try {
if (req.params.id !== req.user.id.toString()) {
// Send error in here.
}
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
res.status(200).json(updateuser);
} catch (error) {
next(error);
}
};

Related

error sending header, express comparison code

I wondered. And in general, I need help.
app.get('/admin', async (req,res) => {
let tq = await User.findOne({ where: { link: req.params.userId } })
// if (tq.status === req.originalUrl.split('/')[1])
//myname(req, res)
return res.render('/admin')
// } else {
// res.end('w')
// }
}
if I do this, then I will not get mistakes. (spoiler: cors on)
async function myname(req, res) {
let tq = await User.findOne({ where: { link: req.params.userId } })
if (tq.status === req.originalUrl.split('/')[1]) {
next()
} else {
res.end('w')
}
}
//and I will connect it to the code above (imagine that there are no crutches, a regular render of the page
then we get an error of something type: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
what's my problem? Do I have to use conditional operators everywhere?...

Send data from React Native front end to Express back end

I'm new to React and building a MERN stack. I'm having issues passing a variable from my front end to my back end. I've tried using console logs to debug and I can see that my request body is coming up blank. I've spent hours trying to figure out what I'm doing wrong but I haven't had any breakthrough yet.
Please see my code below.
User Frontend Hook
const fetchUser = (dispatch) => {
return async () => {
const email = await AsyncStorage.getItem("email");
console.log("async email:", email);
try {
console.log("sending email:", email);
const userInfo = await trackerApi.get("/users", {email});
dispatch({ type: "fetch_users", payload: userInfo.data });
} catch (err) {
console.log(err);
}
};
};
Express/Axios Backend
router.get("/users", async (req, res) => {
console.log("Request Body:", req.body);
try {
const { email } = req.body;
// console.log("Email for req: ", email);
const user = await User.find({ email: email });
console.log("Users for req: ", user);
res.send(user);
} catch (err) {
console.log(err);
}
});
The issue is related to the HTTP method, your route/API is GET call and get method does not have the body, either update to post or use req.query.
Client
const userInfo = await trackerApi.post("/users", {email});
// OR
const userInfo = await trackerApi.post("/users", { data: {email});
Server
router.post("/users", async (req, res) => {

addProject is not a function (Sequelize)

In my app I've established an association between the User and Project table. using this code:
User.belongsToMany(Project, {
through: "users_projects"
});
Project.belongsToMany(User, {
through: "users_projects"
});
When I do a simple post request I get the following error:
currentUser.addProject is not a function
app.post("/project", async (req, res, next) => {
try {
const project = await Project.findOrCreate({
where: {
name: req.body.name,
content: req.body.content
}
});
const currentUser = await User.findAll({
where: { id: req.body.userId }
});
console.log(currentUser);
await currentUser.addProject(project[0]);
res.json(project[0]);
} catch (error) {
next(error);
}
});
What could cause this problem?
findAll returns an array, so your code should be
await currentUser[0].addProject(project[0])
However, if you are querying with id, you can use findByPk to get object.
const currentUser = await User.findByPk(req.body.userId);
await currentUser.addProject(project[0])

Node JS throwing cannot set headers after they are sent to the client, after using mongoose.removeOne

I have a method that deletes products and before it does it check if the user who is trying to delete the product is the user who created it. When i execute it with Insomnia it successfully removes the product but i get an error on the console saying cannot set headers after they are sent to the client.
My method:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, () => {
return res.status(401).json("Not authorized");
})
.then(() => {
return res.status(200).json("Product deleted");
})
.catch((err) => {
return res.status(500).json({
error: err,
});
});
};
I'm pretty sure this is happening because I'm chaining a .then() and .catch() after executing it.
I tried to do this but it didn't work because the err parameter that I'm sending to the callback function is null.:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, (err) => {
if (err) {
return res.status(401).json("Not authorized");
}
return res.status(200).json("Product deleted");
});
};
When i tried this second approach I always got the 200 status, meanwhile the product didn't delete.
Any idea how to deal with this?
You can try something like this:
Product.deleteOne({ _id: id, userId: req.user._id }, (err, result) => {
if(err) {
return "something"
}
return "something else"
});
or: in async / await way
try {
await Product.deleteOne({ _id: id, userId: req.user._id });
} catch (err) {
// handle error here
}
By the way, why you are passing userId at the deleteOne method?

Fetch data from api(RESTful) db(mongodb) according to user input

I have created an api using nodejs, express and mongodb. I am fetching data now without sending any query. But in my frontend I have an input where the user can search for a recipe. So for example if a user types "Today" i should get response related to today only. How to check that in db and retrieve data?
module.exports = function(app, db) {
app.get("/dates/", (req, res) => {
db
.collection("dates")
.find()
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});
While making the api call , pass the dish as query parameter
For example '/recipes/?dish="Pizza" '
and in the express use the following.
module.exports = function(app, db) {
app.get("/recipes/", (req, res) => {
let queryDish = req.query.dish; // assuming /recipes/?dish="Pizza"
let query = { 'title' : { '$regex' : queryDish, '$options' : 'i' } };
db
.collection("recipes")
.find(query)
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});

Categories

Resources