0

hello i am trying to build a search system for a social media application, where people can find users but i want it to be that if the user is typing a word, the search starts and the more word the user inputs the more the searches become better. for example if i type in p...the database shows all the users that starts with p, then if i type in a the db shows all the users that starts with pa...and so on, is there a method like that for mongoose or do i have to use the front end to make that happen..btw im using react

2 Answers2

0

You could probably write a mongo regex query to get this done!

db.getCollection('fruits').find({'fruit_name': { $regex: 'Apple', $options: 'i'}})

option i performs a case insensitive search. Call the search endpoint on every onChange of the input search field.

Mahesh Kumaran
  • 887
  • 2
  • 12
  • 30
  • sorry please i do not understand please could you elaborate? –  Jun 23 '20 at 09:42
  • So you must have exposed an endpoint for search right? Add the MongoDB regex query that I have shown you in my answer to that endpoint! Instead of `Apple` put the variable with the search string and you 'll get the results. Modify the collection name and search field accordingly ! – Mahesh Kumaran Jun 23 '20 at 09:45
  • yes i understand that part, i meant how do i implement this in react frontend, so for every text in my input it searches the db –  Jun 23 '20 at 13:37
  • Example before i click the search button, and i type P into the seacrh box, it should already be looking for users starting with p –  Jun 23 '20 at 13:46
  • Yes, hit the api for every change event triggered in react ! If need more help with React can you please post the REACT Code in the question? – Mahesh Kumaran Jun 24 '20 at 04:12
0

I will divide the solution into two parts :

Front-end :

you can send the data as a query string , for example :

user type : p.. , request must be like this :

let search='p..';
example.com?search=search 

Back-end : this link show you how you can read a query string ;

now , i will use this query to find the result in my mongo collection Example :

var query = url_parts.query // my-query; 
db.users.find({"name": /.*query.*/})

Note : I suppose you have some knowledge of HTTP REQUESTS ,NodeJs that to understand what i said

nassim miled
  • 581
  • 1
  • 6
  • 18