How to create search/autocomplete functionality using mongodb and expressjs?

Issue

So basically I want to create a search functionality for my users schema. I would take in a query for a user based on their name and return relevant users.

For example:

query = "leo", response = ["leonel messi", "leonardo dicaprio", …]

I already tried using the text index but since that requires entire words to be inputted, it doesn’t fit my constraints since a query will most likely be characters rather than entire words.

So essentially Im looking to make an autocomplete which returns relevant users based on some input from the user.

How could I accomplish this? Thank you!

Solution

As shown by Dov Rine and rajabraza in the comments, I could simply use a regex to find make such an implementation.

Code:

const searchResults = await Users.find({ name: { $regex: `^${req.params.name}`, $options: 'i' } }).select(["name"]);

Answered By – darkstar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published