1

I have a schema like this:

{
  _id: ObjectId("5a7acda13b808dbed05d6b7e"),
  name: "An Apple eat by Man"
}

For that I wrote the query i.e :

db.Collection.find({post: { $regex: req.body.query, $options: "i" }})
.then(data => {
  console.log(data)
})
.catch(error => {
  console.log(error)
})

So for that Query if I write "An Apple" it return the data, but if I write "eat man" then it will not return data.

Any guess where I am doing wrong, Any help or suggestion is really appreciated

Ankit
  • 951
  • 1
  • 9
  • 29

1 Answers1

0

The problem is your regex. Having the regex /eat man/ will look for strings to contains exactly "eat man" and not the separates words themselves.

Example :

console.log(/eat Man/.test('An Apple eat by Man'));
console.log(/eat by Man/.test('An Apple eat by Man'));
console.log(/eat  Man/.test('An Apple eat by Man'));
console.log(/eat by  Man/.test('An Apple eat by Man'));

You can change your regex to say "Match any string with contains the words 'eat' and 'man'" for example :

console.log(/eat.*Man/.test('An Apple eat by Man'));

In your case, you can do :

// $regex: req.body.query

const req = {
  body: {
    query: 'Man eat',
  },
};

// Will generate something like (?=.*Man)(?=.*eat)
const regex = req.body.query.split(' ').map(x => `(?=.*${x})`).join('');

console.log((new RegExp(regex, 'i')).test('An apply eat by man'));

enter image description here

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69