Loading...
save

How to efficiently implement full-text fuzzy search and matching in Mongoose for a Next.js 15 search bar?

clock icon

asked 75 days ago

message icon

0

eye icon

3

I am trying to build a global search bar in my Next.js 15 application that queries my MongoDB Question collection via Mongoose.

Currently, I am handling the search parsing on the server using a basic $regex match. While it works for exact phrase segments, the performance scales poorly as the database document count grows, and it completely fails to catch simple typos, character order mistakes, or matching across multi-field contexts (like matching phrases simultaneously against both a question's title and its content string body).

Here is my current search extraction logic inside my Server Action file:

1// lib/actions/question.action.ts
2export async function getQuestions(params: GetQuestionsParams) {
3 await dbConnect();
4 const { searchQuery } = params;
5
6 const query: FilterQuery<typeof Question> = {};
7
8 if (searchQuery) {
9 query.$or = [
10 { title: { $regex: searchQuery, $options: "i" } },
11 { content: { $regex: searchQuery, $options: "i" } }
12 ];
13 }
14
15 const questions = await Question.find(query).sort({ createdAt: -1 });
16 return { questions };
17}
1// lib/actions/question.action.ts
2export async function getQuestions(params: GetQuestionsParams) {
3 await dbConnect();
4 const { searchQuery } = params;
5
6 const query: FilterQuery<typeof Question> = {};
7
8 if (searchQuery) {
9 query.$or = [
10 { title: { $regex: searchQuery, $options: "i" } },
11 { content: { $regex: searchQuery, $options: "i" } }
12 ];
13 }
14
15 const questions = await Question.find(query).sort({ createdAt: -1 });
16 return { questions };
17}

0 Answers

Empty state illustration

No Answers Found

The answer board is empty. Make it rain with your brilliant answer.

1

Write your answer here

Top Questions