Getting 0 result on search in Node JS

Viewed 66

I have Created a Node JS API for Search and stored some data in MongoDB. My data is stored like example:

FN02 ROL

FN02 ROM

FN02 RON

FN02 ROO

FN02 ROS

FN02 ROT

FN02 ROV

FN02 ROW

FN02 ROX

FN02 ROY

So when i search with fn02 it works well but when i add one more parameter like fno2r it doesn't work i think it would be because of space but not sure so i trim that space but still it doesn't work any idea.

My search code is searchquery is my search data

let regexexp = new RegExp(searchquery,'i');
s = {"name": regexexp};

function callback(totalcount){
     db.collection("customers").find(s).limit(16).toArray(function(err, res) {
        if (err) throw err;
        responsedata = { status: true,error : false,data : res };
        resolve(responsedata);
      });
  }

Any idea what i'm doing wrong here ?

1 Answers

I'd suggest making any whitespace in the input optional:

let regexexp = new RegExp(searchquery.split('').join('\\s*'),'i');

Here,

  • searchquery.split('') - splits the searchquery into separate chars
  • .join('\\s*') - joins the splits back with \s* in between each, so that if there is any whitespace between searchquery chars, they could be matched, too.
Related