how to get data by name as well as its id in express route prameter, mongoose

Issue

finding data by id, route parameter like this

url is : http://localhost:8000/products/60d1789867bc6624403ade6e

// getting a single product
router.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
    const result = await Product.findById(id);
    return res.json({
    result,
  });
  } catch (error) {
     return res.status(400).json({
     msg: "product not found",
     error: error,
  });
 }
});

but when I try to find by name
url : http://localhost:8000/products/product_name

// getting products by name
  router.get("/:name", async (req, res, next) => {
  const name = req.params.name;
  try {
      const result = await Product.find({ name: name });
      return res.json({
      result,
   });
   } catch (error) {
       return res.status(400).json({
       msg: "product not found",
       error: error,
    });
   }
  });  

this block of code does not execute, url req goes to :id parameter

how to differenciate this

Solution

You can’t. For Express, both routes are same (giving the different name to variable doesn’t work here).

You need to go with either one of the mentioned route and need to modifies the logic to find the product data.

router.get("/:id_or_name", async (req, res, next) => {

Get the value of this id_or_name variable and check if it is the valid ObjectId is not using mongoose.Types.ObjectId.isValid(). If it is valid then execute the .findById() else go for .find() method.

const id_or_name = req.params.id_or_name;

// ... code ...
if (mongoose.Types.ObjectId.isValid(id_or_name)) {
  result = await Product.findById(id_or_name);
} else {
  result = await Product.find({ firstName: id_or_name });
}
// ... code ...

Answered By – Viral Patel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published