Prajwol Adhikari
Prajwol Adhikari

Reputation: 83

Regex search should not return anything if search string is empty in MongoDB

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

Answers (1)

codemonkey
codemonkey

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

Related Questions