Robust Search with $or
Beyond Exact Matches
Section titled “Beyond Exact Matches”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.
Filtering on Multiple Fields
Section titled “Filtering on Multiple Fields”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);}Deconstructing the Query
Section titled “Deconstructing the Query”$or: Takes an array of conditions. If any are true, match.$regex: Allows partial matching (“fast” matches “Fastest”).$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.
⏭ Next: Inputting Data
Section titled “⏭ Next: Inputting Data”We can read. Now we must write.