2

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!

darkstar
  • 829
  • 11
  • 23
  • 1
    possible duplicate of: https://stackoverflow.com/questions/32898139/partial-string-matching-in-mongodb – Dov Rine Oct 20 '21 at 06:15
  • 1
    You can make use of regex. MongoDb supports regex queries to perform string pattern matching. This might be helpful https://docs.mongodb.com/manual/reference/operator/query/regex/#mongodb-query-op.-regex – rajabraza Oct 20 '21 at 06:21

1 Answers1

1

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"]);
darkstar
  • 829
  • 11
  • 23