Multiple fields search with node and mongodb

Viewed 474

It's a React, Node, MongoDB and Express project. I am trying to get multiple fields search on my Find Jobs page. The route looks like this :

<Route path="/findjobs/:keyword?/:location?/:category?/:page?">
    <FindJobs />
</Route>

In my redux code, I get the different parameters and I send them to the back end.

  const { data } = await axios.get(`/api/jobs?keyword=${keyword}&location=${location}&category=${category}`);

With the only field "keyword" everything is fine, I manage to display the results.

const getJobs = asyncHandler(async(req, res) => {
    const keyword = req.query.keyword ? {
        title: {
            $regex: req.query.keyword,
            $options: 'i'
        }
    } : {}

    const jobs = await Job.find({ ...keyword });
    res.json(jobs);
})

I would like to know how to do the same thing but with all the fields at once or with only the second or the third field. I also noticed that with React, when I pass the second field while the first is empty, it creates a link like this "localhost:3000/findjobs//newyork". Am i doing something wrong with the optional parameters?

1 Answers

In case anyone is facing the same issue

I was doing wrong, first you need to use query params instead of url params in your Route.

Then you controller function should be something like this :

const getJobs = asyncHandler(async (req, res) => {
  let queryCond = {};

  if (req.query.keyword) {
    queryCond.title = { $regex: req.query.keyword, $options: "i" };
  }
  if (req.query.location) {
    queryCond.location = req.query.location;
  }
  if(req.query.category) {
      queryCond.categories = { $all : [req.query.category] }
  }

  const jobs = await Job.find(queryCond);

  res.json(jobs);
});
Related