In my Node js, I escaped a single quote with the following function
var regescape = function(text) { return text.replace(/[\[\]']+/g, "\\$&"); };
This works great for me. But unexpectedly, I found that I have the string M '$ in my database. Which does not return with my bottom request.
param 1 = "M'$"; var cursor = db.collection('search').find({"searchcontent.name":new RegExp('^'+regescape(param1))}).limit(10);
Also suggest best practices for handling Node JS pass to MongoDB parameter. I am invoking NodeJS from PHP code. And I am sending parameters with rawurlencode() from PHP code. In Node js, I use decodeURI() for the resulting parameters.
Edit:
My PHP code to call Node JS:
function getdetail($data1) { $p1 = $data1; $service_url = 'http://exampleserver:8081/search?param1='.$p1; $curl = curl_init($service_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $curl_response = curl_exec($curl); if ($curl_response === false) { $info = curl_getinfo($curl); curl_close($curl); die('error occured.Please try later'); } curl_close($curl); $decoded = json_decode($curl_response, true); if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') { die('error occured.Please try later'); } return $decoded; }
Node JS code for receiving data:
app.get('/search', function (req, res) { var param1=decodeURI(req.query.param1); MongoClient.connect(url, function(err, db) { assert.equal(null, err); search(param1,db, function(data){ db.close(); res.end(JSON.stringify(data)); }); }); }); var search = function(param1,db, callback) { var cursor = db.collection('search').find({$or:[{"searchcontent.name":new RegExp('^'+regescape(param1))},{"searchcontent.name":new RegExp('^'+regescape(param1.substring(0,4)))}]}).limit(10); cursor.toArray(function(err, items) { callback(items); }); };
This Node JS code is for search, so I used RegEXP() . In other cases, I used the code below:
var cursor = db.collection('employees').find({"dep.name":regescape(param1),"mrg.name":regescape(param2)});