Mongoose: Remove elements from array of objects in Mongo if condition is met

Viewed 1357

I have an array of objects that stores the date of an API request along with the JSON values of the request and response. The issue is I don't want this log to get massive. I need to set a max limit or remove entries older than a particular date.

I'm trying to use a mongo / mongoose query to delete elements of an array when the date value of that object is greater than 5 days.

This is the relevant section the mongo model:


      log: [
        {
          select: false,
          date: {
            type: Date,
            default: Date.now,
            select: false
          },
          request: { type: String, select: false },
          response: { type: String, select: false }
        }
      ]

I've tried using updateMany and $pull


    const fiveDaysAgo = moment()
      .subtract(5, 'day')
      .format('YYYY-MM-DD');

    // Ensure log value exists in collection
    // Remove any log entry older than five days
    Collection.updateMany(
      { log: { $exists: true } },
      { $pull: { 'log.$[].date': { $gte: fiveDaysAgo } } }
    ).then(data => console.log(data));

This produces this error:

(node:1957) UnhandledPromiseRejectionWarning: MongoError: Cannot apply $pull to a non-array value

If there was a way to set a max value of entires in the array of objects, and automatically pop the oldest entry off when the new entry is inserted that would also work for me.

1 Answers

Based on your schema log is just an array of documents which contain a field date so if you want to build a condition for that field your update can look like below:

Collection.updateMany(
    { log: { $exists: true } },
    { $pull: { 'log': { date: { $lte: fiveDaysAgo } } } }
    ).then(...)
Related