MongoDB Node JS avoiding single quote issues

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)}); 
+5
source share
1 answer

The problem is the $ sign. This is a special character, and it must be escaped, because usually it means the end of the input. You need to update the regescape function because it avoids just a single quote and square brackets - so you at least add a dollar sign there.

It also seems that your regescape function regescape not working properly in some cases. For example, try passing this value: test[]' . I think you expect to get test\[\]\' , but actually you get test\[]'

So, to fix and add a dolor sign - it should be something like this:

 var regescape = function(text) { return text.replace(/'|\$|\[|\]/g, "\\$&"); }; 

The pipe (|) means or , so it just eludes any of the characters in the set. You can easily add more characters in the future.

+1
source

Source: https://habr.com/ru/post/1259941/


All Articles