[MONGO] mongoose query get data of current week - fourslickz/notes GitHub Wiki

To query documents in MongoDB using Mongoose that belong to the current week, you can use the Date object in JavaScript to determine the start and end dates of the current week and then query your MongoDB collection based on these dates.

Here’s how you can do it:

Step 1: Calculate the start and end of the current week

const startOfWeek = new Date();
startOfWeek.setHours(0, 0, 0, 0);
startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay()); // Adjust to the start of the week (Sunday)

const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(endOfWeek.getDate() + 6); // Add 6 days to get the end of the week (Saturday)
endOfWeek.setHours(23, 59, 59, 999); // Set to the end of the day

Step 2: Query MongoDB using Mongoose

Assume you have a Post model and want to find posts created within the current week.

const mongoose = require('mongoose');

const Post = mongoose.model('Post', new mongoose.Schema({
    title: String,
    content: String,
    createdAt: {
        type: Date,
        default: Date.now,
    },
}));

const startOfWeek = new Date();
startOfWeek.setHours(0, 0, 0, 0);
startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay()); // Start of the current week (Sunday)

const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(endOfWeek.getDate() + 6); // End of the current week (Saturday)
endOfWeek.setHours(23, 59, 59, 999); // End of the day

Post.find({
    createdAt: {
        $gte: startOfWeek,
        $lte: endOfWeek,
    }
}).then(posts => {
    console.log(posts);
}).catch(err => {
    console.error(err);
});