I’m doing a project on an e-commerce website. here I’m with a problem.
- I have used the get method to retrieve user data from MongoDB
- I have passed the correct parameters and the statement UserId:req.params.userId has been satisfied where we can see in the nodejs terminal.
- I’m looking to get only particular user data with UserId === UserId. But in my result, all the user’s data is popping up.
Im trying this but the solution im getting is all the users data
i have tried using findOne() but the result is this 635ea7e5e931e12c9f851dd3 user details. where the parameter is 63a8a0f77addf42592eed1e5. where im expecting to get the only user which im passing in parameter.
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
The req.params userId is ’63a8a0f77addf42592eed1e5′. i need only this. but it is popping up all the users data.
Node.js terminal showing the parameter is same with userId
Postman showing the response of all users present in the DB but i need only the user details which i had passed in the parameter
2
Answers
I had found the solution for my problem i.e I have used filter method at (
res(200).json(cart.filter(((user)=>user.UserId === req.params.userId)
)This means
UserId
in my model === to the parametersuserId
Here the mongoDB
find
method returns all data in the collection, irrespective of the parameters that we pass in to it. Instead try using thefindOne
method for that collection. So the code with correction will be as follows:You can read more about the method at MongoDB Manual.