0

I am currently creating an animal shelter web app using mern and i have trouble grouping data by date month. so i have this schema for the rescued date:

const animalSchema = new mongoose.Schema({
  date_rescued: {
        type: Date,
        default: Date.now,
    },
})
module.exports = mongoose.model('Animal', animalSchema);

And here on my animal controller backend this is my query for fetching the datas:

exports.getRescuedChart = async(req,res,next) => {
    const rescuedanimals = await Animal.find({}).select(['date_rescued']);
    res.status(200).json({
        success:true,
        rescuedanimals,
    })
}

the data that this function is returning to the state is this: enter image description here

what i want to have is group them by data and count how many object has the same date.

rescuedanimals =[ {
date_rescued: "April", animal_count: 8 } ]

1 Answers1

0

so yeah i just learn how to do it myself so here's what i did.

first is that i installed dataeformat library: 'npm install dateformat' i import it on my project: import dateFormat from 'dateformat';

what i did first is to change the date format and reduce duplicate dates.

const groups = rescuedanimals.reduce(
            (groups, rescued_animal) => {
                const date = dateFormat(rescued_animal.date_rescued[0], "mmmm")
                if (!groups[date]) {
                    groups[date]=[]
                }
                groups[date].push(rescued_animal);
                return groups;
            }, {}
        )

after that i created a new function to put this on an arraay and also to get the legnth of the objects that are in that date.

const groupArrays = Object.keys(groups).map((date) => {
        return {
            date,
            games: groups[date].length
        };
    });

thanks to Austin Greco: https://stackoverflow.com/a/46802505/12398637