Home > OS >  Cannot GET Router Error | Getting data by name or id
Cannot GET Router Error | Getting data by name or id

Time:11-21

Why i'm getting an error whenever I try this code?

  router.get("/", async (req, res) => {
    const shopId = req.params.id;
    const shopName = req.params.shopName;
    try {
        const shop = shopId 
        ? await Shop.findById(shopId)
        : await Shop.findOne({ shopName: shopName });
      const { updatedAt, ...others } = shop._doc;
      res.status(200).json(others);
    } catch (err) {
      res.status(500).json("Shop not found!");
    }
  });

I'm just trying to get the shop data stored in mongodb collection.

Whenever I try it on Postman, I get this error.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /shops/Asos</pre>
</body>

</html>

I don't know what I'm missing here! Or is there any other way to implement this? Getting the data by the name of the shop or the Id

CodePudding user response:

const mongoose = require("mongoose");

router.get("/:id", async (req, res) => {
   const shopIdOrName = req.params.id;
   var shop;
   try {
      // check if its valid id, else its name
      if(mongoose.isValidObjectId(shopIdOrName ){
         shop = await Shop.findById(shopIdOrName )
      } else {
         shop = await Shop.findOne({ shopName: shopIdOrName });
      }
      const { updatedAt, ...others } = shop._doc;
      res.status(200).json(others);
    } catch (err) {
      res.status(500).json("Shop not found!");
    }
  });
  • Related