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.

4
  • 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 ? Commented Dec 1, 2016 at 10:00
  • Did you try a solution like: http://stackoverflow.com/questions/3305561/how-do-i-query-mongodb-with-like Commented Dec 1, 2016 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. Commented Dec 1, 2016 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. Commented Dec 2, 2016 at 5:11

2 Answers 2

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) );
});;
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.