Ensar Eray
Ensar Eray

Reputation: 66

NodeJS, Mongooose - find with regex not returning anything

 const students = await Student.find(
      { name: /\w*(req.body.name)\w*/i },
      'name surname email'
    );

Hello everyone I couldn't understand why this regex find statement do not return anything. I check with data from db on regex control websites and statement is working. But in code it is not returning anything. I am new with regex and actually I want to check name and surname fields contains any given string but for question I simplified it like this. I appreciate any help.

Upvotes: 0

Views: 32

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You need to create regex from your variable first then pass it to the query:

const students = await Student.find(
  { name: new RegExp(`\\\w*${req.body.name}\\\w*`, 'i') },
  ...
);

Upvotes: 1

Related Questions