Reputation: 83
This returns values even if search is an empty string i.e.
const search = req.params.q; // " ";
const books = await Book.find({ title: { $regex: search, $options: "i" } });
//list of books
console.log(books);
How to not return any values if the search string is empty?
Upvotes: 0
Views: 662
Reputation: 7915
Yes, an empty regex will match everything. If you want not to return anything when the search string is empty, then don't even run the find
command. Change your code to account for an empty search string:
const search = req.params.q; // " ";
const books = search ? await Book.find({ title: { $regex: search, $options: "i" } }) : [];
//list of books
console.log(books);
This should do the trick.
Upvotes: 1