Use variables with regular expressions to find data in MongoDB (Meteor APP)

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;

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.

Indeed. You may not realize that “/” is different from /, and after The one 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 explicitly creates regular expressions.

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.

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 5404 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.