Oleksiy
Oleksiy

Reputation: 816

MongoDB query documents created between now and two hours ago

I have a mongodb query in my nodethat finds a document based on few conditions:

Follow.find({
    user: req.user._id
    , followed: req.params.userId
}).populate(populateQuery).exec(function (err, results) {
    next.ifError(err);
    //res.send(results);
    if(results.length > 0){
        console.log('****** found!!!');
        console.log(results);
    }
});

So this works fine. However I need to find records that where created only between now and two hours ago. How do I properly format the date objects inside my query object?

{
    user: req.user._id
    , followed: req.params.userId
    ,dateCreated: {
        $gte: ISODate(<TWO HOURS AGO>),
        $lt: ISODate(<NOW>)
    }
}

Upvotes: 2

Views: 751

Answers (1)

chridam
chridam

Reputation: 103425

Create two date objects that represent the datetime now and 2 hours ago respectively as follows:

// Define
var TWO_HOURS = 2*60*60*1000, // milliseconds
    now = new Date(),
    twoHoursAgoDate = new Date(now.getTime() - TWO_HOURS);

Follow.find({
        user: req.user._id,
        followed: req.params.userId,
        dateCreated: { $gte: twoHoursAgoDate, $lt: now }
    }).populate(populateQuery).exec(function (err, results) {
        next.ifError(err);
        //res.send(results);
        if(results.length > 0){
            console.log('****** found!!!');
            console.log(results);
        }
    });

A better way would be to use the momentjs library which simplifies datetime manipulations, in particular you'd use the subtract() method:

// Define
var now = moment(),
    twoHoursAgoDate = moment().subtract(2, 'hours');

Upvotes: 6

Related Questions