Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Mongo db from node.js is not working

I am using regex to fetch data from mongodb from my node js application which is not working. Here is the code snippet. the query can not match with the set of records.

var analysis_date = '/^'+moment(fromTime).format('YYYY-MM').toString()+'/';
user_analysis.find({
parent_id: usrId,
analysis_date: { 
    $regex : analysis_date 
   }
},function(err, result) {
//some Code goes here});
like image 930
Angshuman Avatar asked Jan 29 '26 23:01

Angshuman


1 Answers

Instead of specifying the regular expression as a string, try passing a RegExp object:

user_analysis.find({
    "parent_id": usrId,
    "analysis_date": new RegExp(analysis_date, 'i')
}, function(err, result) {
    // ...
});

If you want, you can also pass a string, but then you'll need to remove the / delimiters:

user_analysis.find({
    "parent_id": usrId,
    "analysis_date": {
        $regex: '^' + moment(fromTime).format('YYYY-MM').toString(),
        $options: "i"
    }
}, function(err, result) {
    // ...
});
like image 135
Dmytro Shevchenko Avatar answered Jan 31 '26 15:01

Dmytro Shevchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!