Ruham
Ruham

Reputation: 759

If condition doesn't trigger in the Express route

This is really weird, and I can't understand what I'm doing wrong. I have a checkbox that, when checked, sets searchByName parameter to truein some React component. Then, I'm using axios to .get a route that needs to search and return the list of users. If searchByName is true, then MongoDB is queried by name, and when it's false, it queries by using some other parameters.

The problem is, that when I console searchByName in the route, I see it's value properly (either true or false), however, my condition that checks if it's true or false doesn't trigger, and I'm always getting the results for the true case. I added console.log("Im name") and console.log("Im city") to see whether or not the code triggers, but it's always the name case, even if searchByName is false.

Could you help to figure this out?

// @route   GET api/report/:search/:searchByName
// @desc    Get users
// @access  Private
router.get("/:search/:searchByName", auth, async (req, res) => {
  if (req.params.searchByName) {
    console.log("im name");
    try {
      const query = req.params.search;
      const reports = await Report.find({
        name: { $regex: query },
        isPublic: true
      })
        .select([
          "name",
          "status",
          "startDate",
          "country",
          "zipcode",
          "city",
          "address"
        ])
        .populate("users", [
          "name",
          "status",
          "startDate",
          "country",
          "zipcode",
          "city",
          "address"
        ]);

      res.json(reports);
    } catch (err) {
      console.error(err.message);
      res.json(err);
      res.status(500).send("Server Error");
    }
  } else if (!req.params.searchByName) {
    console.log("im city");
    try {
      const query = req.params.search;
      const reports = await Report.find({
        $or: [{ city: { $regex: query } }, { zipcode: { $regex: query } }]
      })
        .select([
          "status",
          "startDate",
          "country",
          "zipcode",
          "city",
          "address"
        ])
        .populate("users", [
          "status",
          "startDate",
          "country",
          "zipcode",
          "city",
          "address"
        ]);

      res.json(reports);
    } catch (err) {
      console.error(err.message);
      res.json(err);
      res.status(500).send("Server Error");
    }
  }
});

Upvotes: 0

Views: 39

Answers (1)

giankotarola
giankotarola

Reputation: 775

Your searchByName param is a string. Use req.params.searchByName === 'true|false' to check if it is true or false.

Upvotes: 1

Related Questions