I have been looking at some other answers on stack overflow and got as far as I could with that. I learnt that I need to create a text index where I define my Schema which I did like this:
productSchema.index({'title': 'text', 'address.city': 'text'});
If I search by just 1 field, ie: title then I get results as I expect.
Product.find( { $text: { $search: searchTerm } } )
But there is something wrong with my query when trying to search by title and city together.
Product.find( { $text: { $search: searchTerm }, $text: { $search: city } } )
I see no error but I get no results even though I know there should be results for my query. I am not sure if it is because address is an object (according to what I see in Compass)
This is how I defined it in my schema using Mongoose
address: {
city: {type: String, required: true }
},
If I do this:
Product.find().and([{ title: searchTerm }, { 'address.city': city }])
it almost works. But I have to type in the exact title of the product. If the product is called "a rubber duck" and I type in "duck" I get no results. If I type in "a rubber duck" and select the city it is listed in I get back a result.
I have just also tried this:
Product.find( { $and: [ {$text: { $search: searchTerm }}, { address: {city : city } } ] } )
Which seems to work but could probably be improved upon!