0

NodeJS

search_key = new RegExp('.*' + req.params.search_key + '.*', 'i');
Item.find({product_name:search_key}).exec(function (err, items) {
    console.log(items) );
});

Here I can search product name with the search_key. But my problem is, my product name is "COMPLAN MILK BISCUITS 100GM". If I search with "BISCUITS COMPLAN", its not finding that product. I need to find "BISCUITS COMPLAN" and "COMPLAN BISCUITS" based on contain in search.

Simon PA
  • 748
  • 13
  • 26
Naveen
  • 757
  • 3
  • 17
  • 41
  • Not complitly sure of what you ask. You want "BISCUITS COMPLAN" to find all products who contain either BISCUITS or COMPLAN ? Or both without being specific order ? – Simon PA Dec 01 '16 at 10:00
  • Did you try a solution like: [http://stackoverflow.com/questions/3305561/how-do-i-query-mongodb-with-like](http://stackoverflow.com/questions/3305561/how-do-i-query-mongodb-with-like) – mcatta Dec 01 '16 at 10:06
  • @SimonPA I have an item with product name complan milk biscuits 100gm.If I search with keyword Complan, Its getting that item. But if I search with Biscuits Complan, Its not finding that item. I need to find that Item If we search with keyword Biscuits Complan. – Naveen Dec 01 '16 at 10:42
  • Since you explicitly search for your "search_key" **somewhere** (that is what you do when adding `.*` before and after forming your regexp), you will never be able to match "complan milk biscuits 100gm" with a search term that this string does not include. – Magnus Bodin Dec 02 '16 at 05:11

2 Answers2

2

you need to create text index to achieve your goal and then search from text indexed field. mongo shell command to create text index for product_name field

db.colectionName.createIndex( { product_name: "text" } );

then you can search using $text and $search . doc

db.collectionName.find({ $text: { $search: "BISCUITS COMPLAN" } });

no need to use new RegExp( just can use like:

Item.find({ $text: { $search: req.params.search_key } }).exec(function (err, items) {
    console.log(items) );
});;
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
0

You need to use the $text operator for that.

So instead of:

Item.find({product_name: search_key})...

Something like:

Item.find({product_name: {$text: {$search: search_key}}})...

Note: You need to have a text index for that.

rsp
  • 107,747
  • 29
  • 201
  • 177