Cant patch mongoDB/express - reactjs

I have a react, redux and mongoDB app with a users collection, each user has a favorites array which I want to update with a patch everytime a user adds a favorite element, but my patch method always returns error with a 404 (Not Found). Here's my code:
Action:
export const saveToUser = info => dispatch => {
axios
.patch('api/users', info)
.then( res => {
dispatch({
type:SAVE_TO_USER,
payload:info
})
dispatch( getUsers() )
}).catch( err => console.log(err))
}
users.js
router.patch('/:id', (req,res) => {
User.update({ googleId: req.body.googleId },
{ $push: { favorites: req.body.site } })
});
server.js
const users = require('./routes/api/users')
app.use('/api/users', users);

Fixed myself. My query was wrong, it shoud be:
router.patch('/', (req,res) => {
User.findByIdAndUpdate(
{ _id: "userId" },
{ favorites: ["Here something"] },
function(err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
});

Related

MongoDB / ReactJS Patch handler / findOneAndUpdate not working

in the following code, I'm attempting to update the Checkpoints field for one of my objects within the projects collection. UpdatedCheckpoints is working correctly, so I believe the first block of code works. But the change isn't logging to the database so it doesn't persist. What's going wrong?
const onApprovedSubmit = useCallback(
async (e) => {
e.preventDefault();
let updatedCheckpoints = props.project.Checkpoints;
updatedCheckpoints[props.checkpointIndex].checkpointSubmitted = true;
console.log('here');
try {
let projectId = props.project._id;
await fetcher('/api/projects', {
method: 'PATCH',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ Checkpoints: updatedCheckpoints }),
id: projectId,
});
toast.success('Your checkpoint has been updated');
} catch (e) {
toast.error(e.message);
}
},
[props],
);
handler.patch(async (req, res) => {
const db = await getMongoDb();
const project = await updateProjectById(db, req.id, req.body);
res.json({ project });
});
export async function updateProjectById(db, id, data) {
return db
.collection('projects')
.findOneAndUpdate(
{ _id: new ObjectId(id) },
{
$set: data,
},
{ returnDocument: 'after' },
)
.then(({ value }) => value);
}

How to make api call with optional payload in React JS

I am trying to call API in React JS with AXIOS. I need to send payload as optional when productID has value.
This is my service.js file
fetchProducts: (payload) => put(`/products`, payload),
fetchProductsProductID: (params, payload) => put(`/products`, payload, { params }),
products.js
useEffect(() => {
if (productID) {
CommonSrv.fetchProductsProductID(
{ productID: productID },
{
data: data,
},
)
.then((resp) => {
console.log(resp)
})
.catch((err) => {
console.log(err)
});
} else {
CommonSrv.fetchProducts({ data: data })
.then((resp) => {
console.log(resp)
})
.catch((err) => {
console.log(err)
});
}
}, [])
within the then and catch blocks same conditions I need to use. Because of productID, I am duplicating my code a lot how can I simply this code.
You can try something like that!
(productID ?
CommonSrv.fetchProductsProductID(
{ productID: productID },
{
data: data,
},
)
:
CommonSrv.fetchProducts({ data: data }))
).then(.....).catch(...)

Internal server error 500 react post to firebase

I'm getting a 500 error when posting to my firebase database. However, when I post via postman, it works fine, thus I'm having a lot of trouble debugging this. For the moment, I've hardcoded the categoryId and also the newRow, to make sure there wasn't a problem with my state somehow.
I think the handleSubmit is the only relevant function
handleSubmit = (event) => {
event.preventDefault();
const categoryId = "1RegisterInfo";
const newRow = {
index: "3",
body: "this.state.body",
dataType: "this.state.dataType",
visit: "test",
};
this.props.postRow(categoryId, { newRow });
};
action
export const postRow = (categoryId, rowData) => (dispatch) => {
dispatch({ type: "LOADING_UI" });
axios
.post(`/category/${categoryId}`, rowData)
.then((res) => {
dispatch({
type: "POST_ROW",
payload: res.data,
});
dispatch(clearErrors());
})
.catch((err) => {
dispatch({
type: "SET_ERRORS",
payload: err.response.data,
});
});
};
cloud function
exports.postRow = (req, res) => {
if (req.body.body.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.index.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.dataType.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.visit.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
const newRow = {
index: req.body.index,
dataType: req.body.dataType,
visit: req.body.visit,
body: req.body.body,
createdAt: new Date().toISOString(),
categoryId: req.params.categoryId,
disapproveCount: 0,
approveCount: 0,
};
db.doc(`/categories/${req.params.categoryId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: "Category not found" });
}
})
.then(() => {
return db.collection("rows").add(newRow);
})
.then(() => {
res.json(newRow);
})
.catch((err) => {
console.log(err);
res.status(500).json({ error: "Something went wrong" });
});
};
Any help appreciated!
You're not sending the right payload.
{ newRow }
is the same as
{
newRow: {
index: '3',
body: this.state.body,
dataType: this.state.dataType,
visit: 'test',
},
}
You're passing the above data in the request body and so req.body.body is undefined causing req.body.body.trim() to fail.
this.props.postRow(categoryId, { newRow })
should be
this.props.postRow(categoryId, newRow)
I would recommend using Joi or something similar to validate the request payload before trying to do any other operation.

I have data on the front end but it's undefined in the back end

Hello guys i have a problem with my data on the fetch indeed on the front side i do this to fetch my data:
() => {
const data = {clubChoix: element.nomClub};
const options = {
method: 'POST',
body: data,
};
fetch('http://localhost:8080/inscription/choixclub', options)
.then((response) => {
return response.json();
})
.then(
(responseData) => {
console.log(responseData);
},
(err) => {
console.log(err);
},
);
})
And the i put a console.log to make sure that what i send is real
(console.log(element.nomClub),
The result of this one is:
LOG: Nimes Olympique
In my thought the "const data = {choixClub: element.nomClub};" in the data is like a req.body.clubChoix but in the back end so why when i console log it the req.body it's undefined ?
in case you want to see my back end there it is:
choixClub: (req, res) => {
User.updateOne(
{ _id: "5f47a46e36588f5e2a1e4f35" },
{
$set: {
club: req.body.clubChoix,
},
},
(err) => {
if (err) {
console.log(err);
res.json({ message: "une erreur s'est produite" });
} else {
console.log(req.body.clubChoix);
res.json({ message: "Votre club a bien été enregistré" });
}
}
);
},

Dispatch call didn't go to the updatePost action creator but post got updated

I tried to update the post by submitting the edit form, and on handleSubmit, I dispatched to the updatePost action creator, but it turns out, it doesn't even go to the action creator. Straight goes to the controller. I'm wondering why does it happening, and do I even need a updatePost action here? Also, it's not redirecting after submitting the form to the route /profile/:username/posts.
Here is the code below.
handleSubmit = () => {
const id = this.props.match.params.id
const username = this.props.auth.user.username
const postData = {
title: this.state.title,
description: this.state.description,
}
this.props.dispatch(updatePost(id, postData), () => {
this.props.history.push(`/profile/${username}/posts`)
})
}
---
export const updatePost = (id, postData, redirect) => {
return async (dispatch) => {
dispatch({ type: "UPDATING_POST_START" })
try {
const res = await axios.put(
`http://localhost:3000/api/v1/posts/${id}/edit`,
postData
)
dispatch({
type: "UPDATING_POST_START",
data: res.data,
})
redirect()
} catch (error) {
dispatch({
type: "UPDATING_POST_FAILURE",
data: { error: "Something went wrong" },
})
}
}
}
---
editPost: async (req, res, next) => {
try {
const postData = {
title: req.body.title,
description: req.body.description,
}
const post = await Post.findByIdAndUpdate(req.params.id, postData, {
new: true,
})
if (!post) {
return res.status(404).json({ message: "No post found " })
}
return res.status(200).json({ post })
} catch (error) {
return next(error)
}
}
handleSubmit knows nothing about dispatch. Try dispatching updatePost like this:
handleSubmit = () => {
return dispatch => {
const id = this.props.match.params.id
const username = this.props.auth.user.username
const postData = {
title: this.state.title,
description: this.state.description,
};
dispatch(updatePost(id, postData), () => {
history.push(`/profile/${username}/posts`)
})
}
}
If I misunderstood something, please send more code where you use it.

Resources