0

I want to use regex to find records that match certain pattern on Express.js using MongoDB.

Here is my code

var urlList = [];
var db = req.db;
var collection = db.get('project');

var regex = '/^'+url+'/';
console.log('regex = '+regex);
collection.find({url: { $regex: regex, $options: 'i' }},function(err,list){

    console.log('length = '+list.length);
    var arrayUrl = [];
    for (var i=0;i<list.length;i++){
        console.log(list[i].url);
        arrayUrl.push(list[i].url);
    }
});

But I got list.length = 0 although the database contains the records that match the pattern for sure.

Using the following command on cmd

db.project.find({url:{$regex:/^Projek-1/,$options: 'i'}});

I got the results I want.

How to use regex on express.js to find matched records in MongoDB database?

3
  • 1
    you are passing string instead of regex object. Try using new RegExp Commented Jul 10, 2015 at 14:35
  • You are using URL string as a regex? You will most likely have to escape it: var regex = new RegExp("^"+url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'i');, and remove the , $options: 'i' from the later code. Please check. Commented Jul 10, 2015 at 14:40
  • I am not sure you see that, but ^ makes the regex match at the beginning of the string only. You will need to remove it if you want to match multiple occurrences of a pattern. Commented Jul 10, 2015 at 14:48

1 Answer 1

2

First, you don't really need to use $regex, you'll do fine with url: /foobar/i.

Anyway, the problem is that you are not creating a proper RegExp object, only a string that looks like one. Use a proper one by creating a new instance of RegExp

Example:

var re = new RegExp("^" + url);

...

find({url: re})
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.