Reputation: 322
I've defined a Request Schema:
var RequestSchema = new Schema({
date: {
type: Date,
required: true,
default: Date.now
},
status: {
type: String,
enum: ['Open', 'Closed'],
required: true,
default: 'Open'
}
});
Consider the following documents:
{ status: 'Closed',
date: 2018-08-15T22:43:55.073Z,
_id: 5b61b3b8de9c7252efb77238,
__v: 0 }
{ status: 'Open',
date: 2019-08-15T22:43:55.073Z,
_id: 5b61b3b8de9c7252efb77239,
__v: 0 }
What I'm trying to achieve is simple but I can't seem to make it work. I need a list with all the years that requests were made, e.g., if we consider the documents shown above, I'd like to get the following list as a result:
['2018', '2019']
I'm new to the webdev world, so the most straightforward solution that I could think of was the following:
var years = [];
for (var i = 0; i < 100; i++) {
var start = new Date(2018 + i, 1, 1);
var end = new Date(2018 + i, 12, 31);
Request.findOne({ date: { $gte: start, $lt: end } })
.then(function(request) {
if (request) {
years.push(2018 + i);
}
});
}
res.json(years);
It is pretty obvious that it won't work because the variable years won't change since years.push() is executed from a callback function. I thought I could find a work around but up until now I couldn't.
Any help would be appreciated!
Upvotes: 0
Views: 909
Reputation: 18515
A query that would do this for you in mongoDB would be something like this:
db.getCollection('<YourCollectionName>').aggregate([
{ $project: { _id: 0, year: { $year: "$date" }}},
{ $group: { "_id": null, years: { $push: "$year" } } }
])
it would give you result like this:
{
"_id" : null,
"years" : [2018, 2019]
}
Now you have the years array.
In your query you are doing findOne
but you kind of need aggregation to get group by year type result. I am sure there are other ways to get the result with MongoDB query but that should get you started.
So all you need is to convert that to mongoose ... should be something among the lines of:
const aggregate = Model.aggregate([
{ $project: { _id; 0, year: { $year: "$date" } } },
{ $group: { "_id": null, years: { $push: "$year" } } }
]);
Have not tested it so proceed with caution :)
Upvotes: 1