- Published on
How to Filter by Start Date and End Date in Mongoose
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Sometimes, we'll need to filter date in while fetching data from Mongodb using mongoose.
For example, let's say we've a transaction schema and want to fetch all the transactions that has occurred in particular period.
Here's how to do it:
// Transaction.js model
import mongoose from 'mongoose';
const { Schema } = mongoose;
const transactionSchema = new Schema({
date: Date,
// ....
});
export default mongoose.models.Transaction ||
mongoose.model('Transaction', transactionSchema);
// fetchCurrentMonthTransactions.js
import mongoose from 'mongoose';
const Transaction = mongoose.model('Transaction');
// 👉 https://nesin.io/blog/get-start-end-date-of-month-in-javascript
const date = new Date();
const month = date.getMonth();
const year = date.getFullYear();
const startDate = new Date(year, month, 1);
const endDate = new Date(year, month + 1, 0);
const fetchTransactions = async () => {
const filters = {
date: {
$gte: startDate,
$lt: endDate,
},
};
return Transaction.find({}).where(filters);
};