ndemoreau
ndemoreau

Reputation: 3869

Meteorjs Mongodb how to query a date with momentjs

In Meteor, I create a winner document this way:

var winner = {
                participant_id: array[randomIndex]["_id"], //don't worry about the array[randomIndex]
                creation_date: new Date()
            };
id = Winners.insert(winner);

Later, I want to know how many winners I have today. I tried it many ways, but I couldn't succeed to get the right result.

The last thing I tried is this one:

Winners.find({creation_date: {"$gte": moment().startOf('day'), "$lt": moment().add('days',1)}}).count();

But the result is always equal to zero.

I guess the reason is that moment().startOf('day') is not a date object but I've no clue how to query it the right way.

Upvotes: 3

Views: 3434

Answers (2)

David Weldon
David Weldon

Reputation: 64342

You need to convert the moment object back to a Date so meteor/mongo can process the query. You can do that by appending a call to toDate like so:

var startDate = moment().startOf('day').toDate();
var endDate = moment().add('days',1).toDate();
Winners.find({creation_date: {$gte: startDate, $lt: endDate}}).count();

Upvotes: 13

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

Try this:

// the number of milliseconds since 1970/01/01:
creation_date:new Date().getTime()

and

// you can still use moment:
moment().startOf('day').valueOf()

// query:
Winners.find({
   creation_date: {
     "$gte": moment().startOf('day').valueOf(),
     "$lt":  moment().add('days',1).valueOf()
   }
}).count();

Upvotes: 1

Related Questions