Home > Back-end >  how to get a particular user data from MongoDB in node.js
how to get a particular user data from MongoDB in node.js

Time:01-24

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

CodePudding user response:

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.

CodePudding user response:

ihad 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);
  }
}); ```
  • Related