3

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});
2
  • Did you manage to solve the problem? Commented Mar 20, 2017 at 7:44
  • Yes it worked with the second way you mentioned. Commented Mar 20, 2017 at 19:45

1 Answer 1

3

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) {
    // ...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.