user3451784
user3451784

Reputation: 33

Use variable with regex to find data in mongodb (Meteor app)

I need to get data from Mongodb that in dependence of what I am searching. In the next two examples it work fine:
//example 1;

var variable = "car"; Items.find({"description": variable}).fetch();

//example2;

Items.find({"description": /.*car.*/}).fetch();

but, when I want to combine variable with regex in MongoDB query it returns nothing, what am I doing wrong:

Items.find({"description": /.*variable.*/}).fetch();
Items.find({"description": "/.*"+variable+".*/"}).fetch();

Thanks in advance.

Upvotes: 3

Views: 11835

Answers (3)

Aboobakkar P S
Aboobakkar P S

Reputation: 806

The Answer is each keyword by search

Items.find({"description": {
                        '$regex': new RegExp(variable, "i")
                    }}).fetch();

Upvotes: 3

JSEvgeny
JSEvgeny

Reputation: 2750

And if you need it to be case-insensitive then you should use regex like this:

new RegExp(".*"+keyword+".*", "i")

Upvotes: 6

Christian Fritz
Christian Fritz

Reputation: 21384

Indeed. You may not be realizing that "/" is not the same as / and the latter does not have a semantics for concatenation (like + for strings) as afar as I know of (but I might be wrong). The latter syntax is an inline/shorthand constructor for the RegExp class. That said it is easy to fix, just create the regex explicitly using new RegExp.

In your case, however, I would recommend to use mongodb's $regex construct:

Items.find({"description": {$regex: ".*" + variable + ".*"}}).fetch();

For more details see the documentation on $regex.

Upvotes: 22

Related Questions