I use react for frontend.
Then I do a find method everything works perfecly. Now the I do findOne method that's another story, I always got in catch and 404 error.
router.get("/", auth, postCtrl.findFicheUser); // this routes works perfectly
router.get("/:id", auth, postCtrl.findSingleFicheUser);
exports.findSingleFicheUser = (req, res, next) => {
console.log("req.params.id==>", req.params.id);
// FicheUser.findById(req.params.id)
FicheUser.findOne({ _id: req.params.id })
.then((ficheUser) => {
if (!ficheUser) {
throw new Error("ficheUser not found");
}
console.log("ficheUser==>", ficheUser);
res.status(200).json({ msg: "ficheUser found", ficheUser });
})
.catch((error) => {
res.status(404).json({ msg: "ficheUser not found", error });
});
};
//In react this is how I do my fetch
const FicheUser = () => {
const authCtx = useContext(AuthContext);
// const { id } = useParams();
// C'est quoi mon objectif: de passer les informations de ficheUser
// recuperer tous les fichiers d'un userId
// comment je fais pour acceder au ficheuser d'un userId
const url = `http://localhost:3000/api/ficheUser/${authCtx.userId}`;
// en faite ma route est tjs le meme ya pas le /:id
const fetchHandler = async () => {
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authCtx.token}`,
},
});
const dataResponse = await response.json();
if (response.ok) {
console.log("dataResponse ==>", dataResponse);
} else {
throw new Error(
`Failed to fetch data (${response.status}): ${dataResponse.message} `
);
}
} catch (error) {
console.log("Probleme serveur la req n'est pas parti");
console.log(error);
}
};
const isLoggedIn = authCtx.isLoggedIn;
// console.log(isLoggedIn);
if (isLoggedIn) {
fetchHandler();
// console.log()
}
I get this in my console:
Probleme serveur la req n'est pas parti
FicheUser.js:39 Error: Failed to fetch data (404): undefined
at fetchHandler (FicheUser.js:33:1)
:7000/ficheUser/6414…4c1
This is my Mongo database _id: ObjectId('64148c621b64390be9b21ea2') userId:"64148befb3095018307b3840" age:1 nom:"" prenom:"test1" __v:0
I try the findOne method I expected that the params in the url and the userId of mongoDb matches. Instead geet a 404 error
ps: You can see in the image my userId matches.
I fixed my issue. It was in the line:
FicheUser.findOne({ _id: req.params.id })
it should be:
FicheUser.findOne({ _userId: req.params.id })
As you can see in the image I was matching the wrong id, instead of calling the userId I was calling the ficheUser's object.