Implement User Search
A search endpoint allows clients to find users using a search term.
For example:
GET /api/v1/users?search=john
The API should match users whose names or email addresses contain the search term.
MongoDB supports regular expressions for pattern matching.
However, arbitrary user-provided regular expressions can be expensive or dangerous. Escape special regex characters and restrict search length.
For large datasets, consider dedicated text indexes or a search engine such as MongoDB Atlas Search.
Case-insensitive regular-expression searches may not efficiently use ordinary indexes. Use suitable indexing or a dedicated search solution for large collections.
function escapeRegex(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export async function searchUsers(search) {
const safeSearch = escapeRegex(search);
const regex = new RegExp(safeSearch, 'i');
return User.find({
$or: [
{ name: regex },
{ email: regex }
]
}).select('-password');
}Escapes regular expression metacharacters before building a case-insensitive search query.
Search parameters allow flexible resource discovery.
Escape untrusted regular-expression input.
Choose indexes according to actual query patterns.