Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make full dynamic search in mongoDB?

I want to make full dynamic search, when user used to type one or two string characters of book in book store UI at search box it should bring all match value from my book table that can be entire my table. The kind of object that user want to search is not important it should bring all matched values.

 const searchObjects = req.query;
 const result =await modelbook.find({
   //this place is for query that i don't know how I should write
 });
 res.status(200).json({resultis: result});
})

and book model has these properties name price Url author ...

like image 696
Sayeed Mahdi Mousavi Avatar asked Jan 25 '26 14:01

Sayeed Mahdi Mousavi


1 Answers

You should use $regex.

const search = asyncWrapper(async (req, res) => {
   var { value } = req.query;

   const result = await modelbook.find({
     $or: [
       { name: { $regex: value, $options: "i" } },
       { price: { $eq: Number(value) ? +value : 0 } },
       { url: { $regex: value, $options: "i" } },
       { description: { $regex: value, $options: "i" } },
       { author: { $regex: value, $options: "i" } }
     ],
   });
   res.status(200).json({ resultis: result });
 })
like image 72
Sayed Hassan Hussaini Avatar answered Jan 28 '26 08:01

Sayed Hassan Hussaini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!