skip to Main Content
exports.findByTable = (req, res) => {
 console.log(req);
 const table = req.params.table;
 const text = req.params.text;
 Employee.find({[req.params.table]: "/.*"+[req.params.text]+".*/i"})
.then(data => {
  if (!data)
    res.status(404).send({ message: "Not found Employee with id " +[req.params.text]});
  else res.send(data);
  })`your text`
.catch(err => {
  res
    .status(500)
    .send({ message: "Error retrieving Employee with id=" + [req.params.text] });
});
};

i want to search the data by table name coming from request and the search word that is coming from request and i want to use where clause `

2

Answers


  1. You can create a filter object then set it’s properties and values like so:

    const filter = {};
    filter[req.params['table']] = './*' + req.params['text'] + '.*/i';;
    

    Then just pass the filter object into the model.find() like so:

    Employee.find(filter){...};
    
    Login or Signup to reply.
  2. To search using a variable in MongoDB with Node.js, you’ll want to use regular expressions to achieve that "LIKE" behavior.

    Here’s a tweak to your code:

    exports.findByTable = (req, res) => {
      const table = req.params.table;
      const text = req.params.text;
      
      const query = {};
      query[table] = { $regex: new RegExp(text, 'i') }; // i flag for case-insensitive
    
      Employee.find(query)
        .then(data => {
          if (!data.length) {
            res.status(404).send({ message: `No results found for ${text} in ${table}` });
          } else {
            res.send(data);
          }
        })
        .catch(err => {
          res.status(500).send({ message: "Error retrieving data" });
        });
    };
    

    This uses the $regex operator to perform a case-insensitive search based on the table and text you’ve received.

    Remember, MongoDB’s $regex might not be super performant on large datasets, so consider using indexing and other optimization techniques if needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search