skip to Main Content

I’m doing a project on an e-commerce website. here I’m with a problem.

  1. I have used the get method to retrieve user data from MongoDB
  2. I have passed the correct parameters and the statement UserId:req.params.userId has been satisfied where we can see in the nodejs terminal.
  3. 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

enter image description here

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

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    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

    1. Using filter method UserId in my model === to the parameters userId
    router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
      try {
        const cart = await Cart.find( 
        {userId : req.params.userId});
        console.log("parameter: "+req.params.userId)
          res.status(200).json(cart.filter((user)=>user.UserId === req.params.userId));
         console.log(cart.filter((user)=>user.UserId === req.params.userId))
      } catch (err) {
        res.status(500).json(err);
      }
    });
    

  2. Here the mongoDB find method returns all data in the collection, irrespective of the parameters that we pass in to it. Instead try using the findOne method for that collection. So the code with correction will be as follows:

    router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
      try {
        const cart = await Cart.findOne( 
        {userId : req.params.userId});
        console.log("parameter: "+req.params.userId)
         return res.status(200).json(cart);
      } catch (err) {
        res.status(500).json(err);
      }
    

    You can read more about the method at MongoDB Manual.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search