Search code examples
javascriptnode.jsmongodbsearchadvanced-search

Search any word in string mongodb with node js


I want to create advanced search in project that is in Node JS with Mongo DB. I have created a field in DB that is search-key. user can type any word in text box and i want to match in this word in string and fetch the result. below my db structure and code. my code work only match first word of string not search in all string.

DB : 
{
"_id": ObjectId("001"),
 "searchkey": "Test Product Test Product T-shirt Half sleeves Adidas"
} 
{
"_id": ObjectId("123"), 
 "searchkey": "boy test Product Test Product T-shirt Half sleeves Nike"
} 
{
"_id": ObjectId("456"), 
 "searchkey": "girl test Product Summer Product T-shirt full sleeves Adidas"
} 
{
"_id": ObjectId("789"), 
 "searchkey": "any product any Product any Product T-shirt full sleeves Adidas"
} 
{
"_id": ObjectId("1010"), 
 "searchkey": "woodland Product woodland Product T-shirt Half sleeves woodland"
} 
{
"_id": ObjectId("1212"), 
 "searchkey": "Summer Product Test Product T-shirt Half sleeves Adidas"
} 

My Query : 

Collection.find({searchkey : {$regex: new RegExp('^' + search.toLowerCase(), 'i')},searchkey : {$regex: new RegExp('^' + search.toUpperCase(), 'i')},is_active:true},function(error,fetchSearch){
console.log(fetchSearch);
});

If i search test or TEST it will give me only one result that id is 001 and rest of the result not match from all string.

I want like if i search summer or Summer that it will give me 456 and 1212 _Id data.


Solution

  • You are only checking if the string is starting with the user's search string.

    ^ = means start of string, so '^' + search.toLowerCase() means search for a string which is starting with search.toLowerCase(), and that's it. If it wont start with the search string - it wont match. That's why for test only id 001 get a match.

    Change your search pattern to: '.*' + search.toLowerCase() + '.*' to find the search string anywhere inside the strings.

    Here is the new regex, you can see it is matching 'Summer' with both 456 and 1212