0

I have my mongoose model:

LogSchema = new Schema({
    level : String,
    code: String,
    message: String,
    Timestamp : { 
      type : Date, 
      default: Date.now 
    }
})

I'm trying to delete all documents older than 30 days (Timestamp field) using this code:

var d = new Date();
var older_than = new Date(d.setDate(d.getDate() - 30));
Log.remove({ Timestamp : {$lte : older_than } }, function(err) {
    if (!err) {
        console.log("Clean complete")
    } else {
        console.log("Clean error")
    }
});

I see on console: "Clean complete", but I still have all documents older than 30 days.

Something wrong in my code?

Daniele
  • 3
  • 1
  • 2

2 Answers2

1

Moment is not at all required here. It's a lot of bloat which basically forks the base Date and adds to it.

Instead try this:

const thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 30));

try {
  const { deletedCount } = await Log.deleteMany({ Timestamp: { $lte: thirtyDaysAgo } }).exec()
  console.log(deletedCount, "Logs since", thirtyDaysAgo, "have been cleared")
} catch(e) {
    console.error(e.message)
}

Source: How to get 30 days prior to current date?

If you don't need it to be 30 days, but a month ago instead, you can do this too:

const sameDayLastMonth = new Date(new Date().setMonth(new Date().getMonth() - 1))

try {
  const { deletedCount } = await Log.deleteMany({ Timestamp: { $lte: thirtyDaysAgo } }).exec()
  console.log(deletedCount, "Logs since", sameDayLastMonth, "have been cleared")
} catch(e) {
    console.error(e.message)
}

Source: my head =D.

The 2 things you were missing:

  1. .getDate() & .setDate() will return a number, which then needs to be constructed as a new Date.
  2. You should use .deleteMany() instead of .remove(), to be sure more than one are removed.

Also note, the pattern find().remove() found in the accepted answer isn't required.

0

Better you try as below using moment.js

var moment = require('moment');
var older_than = moment().subtract(30, 'days').toDate();
Log.find({ Timestamp: { $lte: older_than } }).remove().exec().then((RemoveStatus) => {
    console.log("Documents Removed Successfully");
}).catch((err) => {
    console.error('something error');
    console.error(err);
})
Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54