skip to Main Content

I have a dictionary model like this:

const dictionarySchema = new Schema({
    entry: String,
    created: { type: Date, default: Date.now },
});

and I want to select this entry each month after its creation date.

How you do this ?

Something like this gives me the entries older than a month, but this is not what I want:

const conditions = { 
    created: { $lt: minusDays(new Date(), 30) },    
}
const dicEntry = await dbs['en'].Dictionary.find(conditions);

I want a solution to select the entry every 30 days from its creation date.

2

Answers


  1. You might need to contraing the search to the day 30 days ago at 00:00:00 and the next day at 00:00:00

    const thirtyDaysAgoStart = new Date();
    thirtyDaysAgoStart.setDate(thirtyDaysAgoStart.getDate() - 30);
    thirtyDaysAgoStart.setHours(0, 0, 0, 0);
    
    
    // I'm not sure if milliseconds might be important here so I'll just go with 00:00:00 of the day after and use $lt
    const thirtyDaysAgoEnd = new Date(thirtyDaysAgoStart);
    thirtyDaysAgoEnd.setDate(thirtyDaysAgoEnd.getDate() + 1);
    
    
    
    dictionarySchema.find({ created: { $gte: thirtyDaysAgoStart, $lt: thirtyDaysAgoEnd } }, (err, entries) => {
      if (err) {
        console.error(err);
      } else {
        console.log(entries);
      }
    });
    

    As youre doing right now

    created: { $lt: minusDays(new Date(), 30) },
    

    you get all created 30 days ago, 31 days ago, 32 days ago, 33 days ago, etc…

    Login or Signup to reply.
  2. you can utilize the $expr operator in MongoDB along with the $mod operator to calculate the number of days that have passed since the entry’s creation date.

    const currentDate = new Date();
    const conditions = { 
        $expr: {
            $eq: [
                { $mod: [{ $subtract: [currentDate, '$created'] }, 30 * 24 * 60 * 60 * 1000] },
                0
            ]
        }
    };
    
    const dicEntry = await dbs['en'].Dictionary.find(conditions);
    

    hope it’s useful

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search