0

I am using a substring value of "data" to search fields in the database having a substring "data" in them. I currently have two fields of that type. Running the code with hard-coding " /data/i " in the "title" field returns the result but when I insert the variable substring to the query for "title" it returns an empty array.

WORKS

router.post('/search',function(req,res){
  let substring = req.body.substring;
  console.log(substring);
  substring = ('/'+substring+'/i');
  console.log(String(substring));


    data.find({title:/data/i},function(err,found){ //works here 

        if(err) console.log(err);
        console.log(found);
        });
    });

Does Not Work

router.post('/search',function(req,res){
  let substring = req.body.substring;
  console.log(substring);
  substring = ('/'+substring+'/i');
  console.log(String(substring));


    data.find({title:substring},function(err,found){ // doesnt work here

        if(err) console.log(err);
        console.log(found);
        });
    });
  • 2
    `/data/i` is a regex, `'/data/i'` is a string. You’re looking for `new RegExp(substring, 'i')`. See also MongoDB’s collation options. – Ry- May 19 '19 at 00:28
  • Um. I am a beginner in javascript, can you help me solve this issue? – Muhammad Yasir Javed May 19 '19 at 00:29
  • 1
    Note the comment that the [collation options](https://docs.mongodb.com/manual/core/index-case-insensitive/) as mentioned are probably a fair choice if all you are really after is a "case insensitive" **exact match**. If you want a ***partial match*** then that still requires a regex, and as noted on the other link, unless that searches from the "beginning of string" this is not a very performant option. Also `$regex` as an operator allows expressions like `find({ title: { $regex: substring, $options: 'i' } })`. – Neil Lunn May 19 '19 at 01:42

0 Answers0