2014-09-10 64 views
0

這是我的第一篇文章,並且需要知道如何解決我的問題的NodeJS貓鼬發現與價值串聯

我有這樣的代碼

var searchParams = '{}'; 
if(typeof nt !== 'undefined') {searchParams = {ticket: {$regex: nt}};} 
if(typeof tp !== 'undefined') {searchParams = searchParams + {typet: {$regex: tp}};} 
if(typeof st !== 'undefined') {searchParams = searchParams + {status: {$regex: st}};} 

但是,當我試圖把「SearchParams」進入我的發現不工作 這是我的代碼在我查找

db.iModel.find(
     searchParams, 
{status:1,datestart:1,typet:1}, 
     {skip:start,limit:limit}).sort(sortParams).execFind(function (err, IncidentSchema) { 

我認爲可能的問題是與「searchParams + {typet:{$正則表達式:TP}}」這是沒有辦法的辦法來工作。這是因爲我嘗試只有一個參數工作!但蜿蜒嘗試更多的參數不是一個參數工作

與控制檯日誌是簡單的字符串,但更多的參數返回此[對象的對象] [對象的對象]

對不起我的英語我西班牙人

謝謝

回答

0

對MongoDB的查詢被表示爲對象而不是字符串。所以,你不「串聯」,而是「建設」的對象,你會在本機代碼:

var searchParams = {}; 
if(typeof nt !== 'undefined') { searchParams["ticket"] = { $regex: nt } } 
if(typeof tp !== 'undefined') { searchParams["typet"] = { $regex: tp } } 
if(typeof st !== 'undefined') { searchParams["status"] = { $regex: st } } 

console.log(JSON.stringify(searchParams, undefined, 2)); 

只是日誌記錄,所以你可以看到生成的查詢對象是什麼樣子。

另外請注意,MongoDB的查詢參數是默認的「與」操作,所以如果你需要的是一個$or條件在那裏,你推到陣列構建方式要麼這些條件可真:

var searchParams = { "$or": [] }; 
if(typeof nt !== 'undefined') { seachParams["$or"].push({ "ticket": { $regex: nt }}); } 
if(typeof tp !== 'undefined') { searchParams["$or"].push({ "typet": { $regex: tp }}); } 
if(typeof st !== 'undefined') { searchParams["$or"].push({ "status": { $regex: st }}); } 

console.log(JSON.stringify(searchParams, undefined, 2)); 
+0

感謝男人,最後我用Nodejs + jqgrid完成了我的搜索 – JorgeFo 2014-09-11 02:56:25