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
You can create a filter object then set it’s properties and values like so:
Then just pass the
filter
object into themodel.find()
like so: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:
This uses the
$regex
operator to perform a case-insensitive search based on thetable
andtext
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.