2016-03-17 80 views
0

我嘗試按日期範圍過濾查詢動態參數從GET的Node.js/MongoDB的篩選日期範圍

var date_from = req.query['date_from']; 
var date_to = req.query['date_to']; 
var options = {}; 
if(date_from){ 
     if(!options["sentDateTime"]) options["sentDateTime"] = []; 
    var dateFrom = moment(new Date(date_from)).toDate(); 
     options["sentDateTime"]['$qte'] = dateFrom; 
} 

if(date_to){ 
    if(!options["sentDateTime"]) options["sentDateTime"] = []; 
    var dateTo = moment(new Date(date_to)).toDate(); 
     options["sentDateTime"]['$lte'] = dateTo; 
} 

例如我的選擇看起來像

{ sentDateTime: { '$qte': Tue Mar 01 2016 00:00:00 GMT+0000 (GMT) } } 

的代碼休息

db.client.collection('mails_ed').find(options).limit(parseInt(req.query['limit'])).toArray(function(err, docs) { 
// ... 
}) 

但它返回零個文件。

編輯:

後改變了我的對象是這樣的

{ sentDateTime: 
    [ '$qte': Tue Mar 01 2016 00:00:00 GMT+0000 (GMT), 
    '$lte': Fri Mar 18 2016 00:00:00 GMT+0000 (GMT) ] 
} 

正如你可以看到,選擇包裝成數組「[]」我怎樣才能解決這個問題?

+1

這不是Mongo的有效ISO日期字符串。裹在'新Date'當下的對象,而不是相反。 '新的日期(力矩(DATE_TO).utc())'爲我工作 –

+0

感謝對此事發表評論。我去與解決方案,但還是有些不妥。我認爲也許在對象選項看起來它現在看起來如何 – pr0metheus

回答

1

您需要使用大括號而不是方括號來創建一個對象字面。另外,我覺得你的意思是$gte,而不是$qte

var date_from = req.query['date_from']; 
var date_to = req.query['date_to']; 
var options = {}; 
if(date_from){ 
     if(!options["sentDateTime"]) options["sentDateTime"] = {}; 
    var dateFrom = moment(new Date(date_from)).toDate(); 
     options["sentDateTime"]['$gte'] = dateFrom; 
} 

if(date_to){ 
    if(!options["sentDateTime"]) options["sentDateTime"] = {}; 
    var dateTo = moment(new Date(date_to)).toDate(); 
     options["sentDateTime"]['$lte'] = dateTo; 
} 
+0

謝謝,這工作......所以這是錯字失敗.. – pr0metheus