Home > OS >  Check if req.param.dogid / req.param.dogname in Express Mongoose
Check if req.param.dogid / req.param.dogname in Express Mongoose

Time:04-24

I have 2 GET functions in the same file.

one for dogid and the other for dogname.

//Operations for api/dogs/{dogId} route
//get operation
 router.get('/:dogId', async (req,res)=>{   
      try{
          const dog = await Dogs.findById(req.params.dogId);
          res.json(dog);
      }catch(error){
          res.json({message:error});
      }
  
  })

And

//Operations for api/dogs/{dogName} route
 //get operation
 router.get('/:dogName', async (req,res)=>{   
      try{
          const dog = await Dogs.find({'name': { $in: req.params.dogName}})
          res.json(dog);
      }catch(error){
          res.json({message:error});
      }
  
  })

When I try npm start it doesn't give any problem.

But in Postman when I send GET operation for http://localhost:3000/api/dogs/Sasha

then it shows the following:

{
    "message": {
        "stringValue": "\"Sasha\"",
        "valueType": "string",
        "kind": "ObjectId",
        "value": "Sasha",
        "path": "_id",
        "reason": {},
        "name": "CastError",
        "message": "Cast to ObjectId failed for value \"Sasha\" (type string) at path \"_id\" for model \"Doggies\""
    }
}

The code for getting the data with dogname is already present. But since the get function for the dogid route is written before the dogname route it's showing this error.

CodePudding user response:

The problem is that GET api/dogs/:dogId is handling the request since it is written before GET api/dogs/:dogname.

To solve this problem try changing your api design or using different HTTP request methods. For example :

POST api/dogs/:dogId
GET api/dogs/:dogName

or GET api/animals/dogs/:dogId
   GET api/dogs/:dogName

But don't do this:

   GET api/dogs/:dogId
   GET api/dogs/:dogName

CodePudding user response:

As @Mohammad Ismail already pointed out, you need to use different HTTP Method to differentiate between 2 routes.

There's another approach is to use query instead of param
You send the request like localhost:3000/api/dog?dogName=abc
Then in your code: req.query.dogName will get you the value abc

  • Related