Get Type Error when using .countDocuments with mongoDB

28 Views Asked by At

I am learning a coure on Youtube. The youtuber wrote this code and it seems to run on his machine. But when I copy to my file, it gave the error. I followed him thoroughly so that everything works fine till this point. Here is the code of the file.

import { Document, Model } from "mongoose";

interface MonthData {
    month: string;
    count: number;
};

export async function generateLast12MonthsData<T extends Document>(
    model: Model <T>
): Promise<{last12Months:MonthData[]}>{
    const last12Months:MonthData[] = [];
    const currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + 1);

    for(let i=11; i>=0; i--){
        const endDate = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth(),
            currentDate.getDate() - i * 28
        );

        const startDate = new Date(
            endDate.getFullYear(),
            endDate.getMonth(),
            endDate.getDate() - 28
        );

        const monthYear = endDate.toLocaleString(
            'default',
            {
                day: "numeric",
                month: "short",
                year: "numeric",
            }
        );

        const count = await model.countDocuments(
            {
                createdAt: {
                    $gte: startDate,
                    $lt: endDate,
                },
            }
        );


        last12Months.push(
            {
                month: monthYear,
                count,
            }
        )

    }
    return { last12Months };
}

Here is the full error message:

Argument of type '{ createdAt: { $gte: Date; $lt: Date; }; }' is not assignable to parameter of type 'FilterQuery<T>'.
  Type '{ createdAt: { $gte: Date; $lt: Date; }; }' is not assignable to type '{ [P in keyof T]?: Condition<T[P]> | undefined; }'.
0

There are 0 best solutions below