Why can I pass string, but I can not pass variable to query MONGO NODE

0

I want to return a JSON from MongoDB with some filters, the problem is, when I try to pass a variable through the function, it does not work, this is the code:

 async find(req, res) {
   const { filter, input } = req.body;
   console.log(filter);
   console.log(input);
   const clients = await Client.find({ filter : { '$regex' : input, '$options' : 'i' } });
   console.log(clients);
   return res.json(clients);
 },

The logs consoles are:

name
testinput
[]

If I change:

const clients = await Client.find({ filter : { '$regex' : input, '$options' : 'i' } });

by:

const clients = await Client.find({ 'name' : { '$regex' : input, '$options' : 'i' } });

It works, but why can not I pass a variable? I need to search with several different filters

    
asked by anonymous 30.12.2018 / 00:11

1 answer

0

In JavaScript itself, a dictionary can be created in two ways:

var test1 = {name: "Fulano", age: 37}; // forma 1
var test2 = {"name": "Fulano", "age":37}; // forma 2

That is, the key can be set with quotation marks, or without quotation marks.

Given this, when you pass the { filter : { '$regex' : input, '$options' : 'i' } } dictionary as argument / parameter, you are passing a dictionary that has the filter key, since this key definition form is accepts. However, since input is not being set as a key, but rather as a value, JavaScript / NodeJS assumes that you are using a variable.

So, in order to use the (correct) value of the variables, just use the JSON object to convert a string into a dictionary like this:

const clients = await Client.find(JSON.parse('{ "${filter}" : { "$regex" : "${input}", "$options" : "i" } }'));

I hope I have helped!

    
30.12.2018 / 21:25