Sling Academy
Home/Node.js/Mongoose: Find documents since last day, last week, last month

Mongoose: Find documents since last day, last week, last month

Last updated: December 30, 2023

Learn how to query documents using Mongoose by time frame – last day, last week, and last month – with Node.js and JavaScript.

Setting Up the Environment

Create a new Node.js project, install Mongoose, and connect to a MongoDB instance. Define a Mongoose schema to model your data with a date field.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourdb', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;

const dataSchema = new Schema({
  // ... other fields ...
  createdAt: { type: Date, default: Date.now },
});

Finding Documents by Date

Last Day (24 Hours)

Use the find() function with a dynamic date object to retrieve documents from the last 24 hours.

const DataModel = mongoose.model('Data', dataSchema);

async function findLastDayDocuments() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  
  return await DataModel.find({
    createdAt: { $gte: yesterday }
  }).exec();
}

You can also create custom query helpers to encapsulate the process of querying by time frames:

dataSchema.query.byLastDay = function() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return this.find({ createdAt: { $gte: yesterday } });
};

// Usage
DataModel.find().byLastDay().exec();

Last Week (7 Days)

Similar to the last day, adjust the date to target documents created within the last week.

async function findLastWeekDocuments() {
  const lastWeek = new Date();
  lastWeek.setDate(lastWeek.getDate() - 7);
  
  return await DataModel.find({
    createdAt: { $gte: lastWeek }
  }).exec();
}

Last Month

To fetch documents from the last month, calculate the date object accordingly.

async function findLastMonthDocuments() {
  const lastMonth = new Date();
  lastMonth.setMonth(lastMonth.getMonth() - 1);
  
  return await DataModel.find({
    createdAt: { $gte: lastMonth }
  }).exec();
}

Error Handling with Async/Await

When using Async/Await, make sure to handle errors with try/catch blocks to keep your application stable.

async function safeFindLastWeekDocuments() {
  try {
    return await findLastWeekDocuments();
  } catch (error) {
    // handle error
  }
}

Advanced Queries with Aggregation

Use Mongoose’s aggregation framework for more complex time-based queries, such as grouping documents by the week.

async function aggregateDocumentsByWeek() {
  return await DataModel.aggregate([
    {
      $match: {
        createdAt: { $gte: /* your start date */ }
      }
    },
    {
      $group: {
        _id: { week: { $week: '$createdAt' } },
        count: { $sum: 1 }
      }
    }
  ]);}

Conclusion

This tutorial introduced you to time-based document retrieval in Mongoose, iterating from basic to advanced queries. Apply these techniques to make your application’s data querying efficient and powerful.

Next Article: Mongoose: Find Documents That Contain a Given String

Previous Article: Mongoose: Search documents by a given field/property value

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates