Skip to content

Robust Search with $or

A basic search is often too narrow. By using the $or operator, we can tell Mongoose to return a document if the search term appears in either the title OR the description.

data/projects.js

async getProjectList(searchTerm = null) {
let filter = { isActive: true };
if (searchTerm) {
// Check both fields using the $or operator and case-insensitive regex
filter.$or = [
{ title: { $regex: searchTerm, $options: 'i' } },
{ description: { $regex: searchTerm, $options: 'i' } }
];
}
return await Project.find(filter);
}
  1. $or: Takes an array of conditions. If any are true, match.
  2. $regex: Allows partial matching (“fast” matches “Fastest”).
  3. $options: 'i': Case-insensitive (“FAST” matches “fast”).
Professor Solo

This is the ‘Google-lite’ search. It’s not full-text indexing, but for small datasets, it’s incredibly effective.

We can read. Now we must write.