learner learner - 5 months ago 17
Node.js Question

node.js mongodb filter based on date

In node.js from mongodb collection, how do I filter documents of a collection based on the

date_added
field as previous year, previous week and previous month? The
date_added
field is in
ISO Date
Format

{
"_id" : ObjectId("574e68e5ac9fbac82489b689"),
"title" : "car",
"price" : 100,
"date_added" : ISODate("2016-06-01T04:47:33.025Z"),

}

Answer

the best way is to use moment.js
Do npm install moment

var moment = require ('moment')

 function previous_year_artist(req, res, next) {
        var dateTimeTofilter = moment().subtract(1, 'year');
        var filter = {
            "date_added": {
                $gte: new Date(dateTimeTofilter._d)
            }
        };
        db.collection.find(
            filter
        ).toArray(function(err, result) {
            if (err) return next(err);
            res.send(result);
        });

    }

use year,month, week as per your requirment