Pass variable in query MongoDB (JAVASCRIPT)

2

With this query:

const result = await Topic.find( { 'categorieName': { $regex: /^news/i } } )

I can return the categories with news name, the problem is that it is not always news, so I wanted to put a variable in place

How do I do this? I have a variable named category that is already getting the 'news' value, if I put it in the console.log, then I tried this:

const result = await Topic.find(JSON.parse('{ 'categorieName' : { $regex: /^${categoria}/i } }'));

But it did not work, what am I doing wrong?

    
asked by anonymous 03.01.2019 / 20:12

1 answer

2

To create a regular expression object with variables, you need to use the RegExp class:

let reString = 'exemplo';

let re = new RegExp('${reString}[0-9]?', 'i');

console.log(re);

console.log('exemplo3'.match(re));

console.log('erro'.match(re));

The parse function does not interpret regular expressions

    
03.01.2019 / 21:02