Pass variable in Mongodb query (JAVASCRIPT)

Asked

Viewed 185 times

2

With that consultation:

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

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

How do I do that? I have a variable called category that is already receiving the value 'news', if I put in the console.log, so I tried this:

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

But it didn’t work, what I’m doing wrong?

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 function parse does not interpret regular expressions

  • Ahhh understood, regular expressions would be like '', '/' and something else, right? What did I do wrong to replace the const result = await Topic.find( { 'categorieName': { $regex: / news/i } } ) ?? I tried this: https://hastebin.com/imacehigon.js But I got these errors: https://hastebin.com/apufayepav.makefile

  • you do something like: create regular expression let re = new RegExp(${category}[0-9]?, 'i'); and then pass it on the search Topic.find({ categorieName: { $regex: re } });

  • I was flying, using the wrong variable, thanks bro!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.