我正在 YouTube 上学习一门课程。 YouTuber 编写了这段代码,并且似乎可以在他的机器上运行。但是当我复制到我的文件时,它给出了错误。我彻底地跟着他,所以到目前为止一切都很顺利。这是文件的代码。
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 };
}
这是完整的错误消息:
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; }'.
您可以使用聚合代替旧方法 .countDocument,这在大多数情况下不推荐。
collection.aggregate([
// Include any `$match` stages to filter your documents as needed
{ $match: { /* your query conditions here */ } },
// `$count` stage to get the number of documents
{ $count: "totalDocuments" }
])