0

I have lots of records stored in MongoDB, and they're (mostly) written in title-case. Sample prototype:

{
   'name':'Awesome Pair of Jeans',
   'designer':'Company123',
   'description':'This pair of jeans is really great. Navy colour.'
},{
   'name':'awesome jeans part 2',
   'designer':'company123',
   'description':'This pair of jeans is also navy in colour.'
}

In my frontend (built on Angular/Node), I want to give the user the ability to search for records, but as MongoDB's search is case-sensitive I'm having some issues.

Currently, if someone searches for the word "awesome" (lowercase) in the "name" field, the only way I've been able to ensure both awesome and Awesome is returned is to query as follows:

First, the query is wrapped in a regex. So if the user searches for "awesome", it's passed to the query as name:/awesome/i

exports.postsQuery = function(req,res){
    var query = req.params.query; // 'name:/awesome/i'
    var properties = query.split('+');
    var criteria = {};
    properties.forEach(function(property) {
        var propParts = property.split('=');
        criteria[propParts[0]] = eval(propParts[1]); // criteria{name:/awesome/i};
    });

    db.products.find(criteria, function (err, record) {
       // Do stuff
    });
}

This returns the correct results, but I'm wondering how secure it is, and if there's a better way to do this.

Similar to this question: Case insensitive search in Mongo but I'm wondering what is best practices for speed and security.

Community
  • 1
  • 1
JVG
  • 20,198
  • 47
  • 132
  • 210

1 Answers1

1

Instead of building the /awesome/i string, its probably better to pass down awesome and then instead of

criteria[propParts[0]] = eval(propParts[1])

you can do

criteria[propParts[0]] = new RegExp(propParts[1], "i");

which will return the same RegExp you are currently getting but without using eval and using less string manipulation.

go-oleg
  • 19,272
  • 3
  • 43
  • 44