Note that there are some explanatory texts on larger screens.

plurals
  1. POCase insensitivity when searching MongoDB - is eval() ok?
    text
    copied!<p>I have lots of records stored in MongoDB, and they're (mostly) written in title-case. Sample prototype:</p> <pre><code>{ '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.' } </code></pre> <p>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.</p> <p>Currently, if someone searches for the word "awesome" (lowercase) in the "name" field, the only way I've been able to ensure both <code>awesome</code> and <code>Awesome</code> is returned is to query as follows:</p> <p><strong>First, the query is wrapped in a regex. So if the user searches for "awesome", it's passed to the query as <code>name:/awesome/i</code></strong></p> <pre><code>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 }); } </code></pre> <p>This returns the correct results, but I'm wondering how secure it is, and if there's a better way to do this.</p> <p>Similar to this question: <a href="https://stackoverflow.com/questions/8246019/case-insensitive-search-in-mongo">Case insensitive search in Mongo</a> but I'm wondering what is best practices for speed and security.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload