pr0metheus
pr0metheus

Reputation: 488

Node.js / MongoDB Filter date range

I try to filter query by date range dynamically parameters from GET

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;
}

For example my options look like

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

Rest of code

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

But it return zero documents.

Edit:

After changes my object look like this

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

As you can see that options wrap into array '[]' how can i fix it?

Upvotes: 0

Views: 2658

Answers (1)

Ben
Ben

Reputation: 10104

You need to use curly braces instead of square brackets to create an object literal. Also, I think you meant $gte rather than $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;
}

Upvotes: 2

Related Questions