//Example 1;
var variable = "car"; Items.find({"description": variable}).fetch();
//example;
Items.find({"description": /.*car.*/}).fetch();
But when I want to When combining variables with regular expressions in MongoDB queries, it returns nothing. What did I do wrong:
Items.find({"description": /. *variable.*/}).fetch();
Items.find({"description": "/.*"+variable+".*/"}).fetch();
Thanks in advance.
However, in your case, I recommend using mongodb’s $regex construct:
Items .find({"description": {$regex: ".*" + variable + ".*"}}).fetch();
For more information, please refer to the documentation on $ regex
.
I need to get data from Mongodb, depending on what I’m searching for. It works fine in the next two examples:
//Example 1;
var variable = "car"; Items.find({"description": variable} ).fetch();
//Example questions;
Items.find({"description": /.*car.*/}). fetch();
However, when I want to combine variables with regular expressions in MongoDB queries, it returns nothing, what am I doing wrong:
< /p>
Items.find({"description": /.*variable.*/}).fetch();
Items.find({"description": "/.*"+variable+" .*/"}).fetch();
Thanks in advance.
Indeed. You may not realize that the “/” and / Is different, and the latter does not have concatenation semantics (such as strings) as I know (but I may be wrong). The latter syntax is the inline/shorthand constructor of the RegExp class. This shows that it is easy to fix, Just use the new RegExp to explicitly create the regular expression.
However, in your case, I recommend using mongodb’s $regex construct:
Items.find({"description": {$regex: ".*" + variable + ".*"}}).fetch();
For more information, please refer to the documentation on $regex
.