I currently have a large collection of data stored in MongoDB, with most entries written in title-case. For example:
{
'name':'Awesome Pair of Shoes',
'brand':'CompanyABC',
'description':'These shoes are top-notch. Available in black.'
},{
'name':'amazing sneakers',
'brand':'companyXYZ',
'description':'Sneakers that come in various colors and styles.'
}
In my Angular/Node frontend, I want to enable users to search for records. However, due to MongoDB's case-sensitive nature, I am facing some challenges.
Currently, when a user searches for "awesome" (in lowercase) in the "name" field, I have to query as follows to ensure both awesome
and Awesome
are returned:
The query is wrapped in a regex pattern. So if the user searches for "awesome", it's processed as name:/awesome/i
exports.searchQuery = 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, result) {
// Handle the results
});
}
While this method returns the accurate results, I am unsure about its security implications and whether there is a more efficient approach.
This dilemma is similar to the discussion found here: Case insensitive search in Mongo. I am seeking advice on best practices for optimizing speed and ensuring data security.