Nivin Nivin - 4 days ago 5
Node.js Question

How to do contain search in Nodejs And Mongodb

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.

Answer

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) );
});;
Comments