Simple code for getting documents that have a creationDate between two values in mongodb.
If the user provides only one of the values the code should still work and get the documents that have either a creationDate less than or bigger than the given value.
I'm mainly looking for more readability and simplicity.
interface mongoDateFilter {
$gte?: Date;
$lte?: Date;
}
export const getReportsForContent = async (
contentId: ObjectId,
beginDate: Date | undefined,
endDate: Date | undefined,
): Promise<Report[]> => {
const reportsCollection = await getCollection('reports');
const creationDateMongoFilter: mongoDateFilter = {};
if (beginDate) {
creationDateMongoFilter['$gte'] = beginDate;
}
if (endDate) {
creationDateMongoFilter['$lte'] = endDate;
}
let reportsForContent: Report[] = [];
if (beginDate || endDate) {
reportsForContent = await reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
} else {
reportsForContent = await reportsCollection.find({ contentId }).toArray();
}
return reportsForContent;
};
```