Reputation: 104
I would like to fetch MongoDB documents using mongoose. And I want to fetch in such a way that documents fetched are documents created from the beginning of the year till present date. All suggestions will be greatly appreciated. Thanks.
Upvotes: 0
Views: 250
Reputation: 103375
Basing the following from your follow-up comments on the question, with a date field createdAt
you can construct a date range query (using the Date()
constructor to create date instances) and obtain the desired result as follows:
var start = new Date(new Date().getFullYear(), 0, 1), // get first day of current year
end = new Date(); // current date
Model.find({ "createdAt": { "$gte": start, "$lte": end }})
.exec(callback);
Using momentjs library, getting the beginning of the current year date can be achieved by the startOf()
method:
var start = moment().startOf('year'), // set to January 1st, 12:00 am this year
end = moment(); // current date
Upvotes: 1