在我的節點JS,我已經逃脫單引號與以下功能MongoDB的節點JS逃逸單引號的問題
var regescape = function(text) {
return text.replace(/[\[\]']+/g, "\\$&");
};
這是對我工作的罰款。 但突然間我發現我的數據庫中有一個字符串'M'$。下面的查詢沒有返回。
param 1 = "M'$";
var cursor = db.collection('search').find({"searchcontent.name":new RegExp('^'+regescape(param1))}).limit(10);
另請建議處理節點JS參數傳遞給MongoDB的最佳做法。 我從PHP代碼調用NodeJS。我正在從PHP代碼發送參數rawurlencode()
。在節點js中,我使用decodeURI()
來接收參數。
編輯:
我對主叫方節點JS PHP代碼:
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;
}
節點JS代碼接收數據:
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);
});
};
這個節點JS代碼是搜索,所以我使用RegEXP()
。對於其他情況,我使用以下代碼:
var cursor = db.collection('employees').find({"dep.name":regescape(param1),"mrg.name":regescape(param2)});
這裏是否需要正則表達式搜索? – hyades
是的。它是我的網站的搜索查詢。所以正則表達式需要 – Arijit
你是怎麼調用node.js的?通過「捲曲」或通過命令行?你如何在NodeJS中接收參數 - 使用Express或?至於正則表達式,你是否需要^表示「開始行」?如果您顯示如何將條目輸入到Mongo以驗證搜索,將有所幫助。 – Robbie