Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Check if req.param.dogid / req.param.dogname in Express Mongoose

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!