Home > Software engineering >  How can I remove an entire object from an array by its expiry time in mongoose?
How can I remove an entire object from an array by its expiry time in mongoose?

Time:05-13

Doc:

        "notifcations": [
        {
          "title": "Joined the Tournament.",
          "description": "You have registered in the Tournament of Tournament #142, issued ₹10 from your balance.",
          "amount": 10,
          "createdAt": "2022-05-08T12:03:02.431Z",
          "expiresAt": "2022-05-09T12:03:05.983Z",
          "_id": "6277b17968729c2811137fb0"
        },
        {
          "title": "Joined the Tournament.",
          "description": "You have registered in the Tournament of Tournament #143, issued ₹10 from your balance.",
          "amount": 10,
          "createdAt": "2022-05-08T12:03:02.431Z",
          "expiresAt": "2022-05-09T12:03:05.983Z",
          "_id": "6277b17968729c2811137fb0"
        }
      ]

Here, in the notifications array I want to remove all objects that are expired - "expiresAt" in object. Like to remove all object in which are expiresAt < Date.now()

Notifications Array is stored in mongodb and I want to create a function for this to remove expired Notifications.

Any Help Please!?

CodePudding user response:

Probably the simplest method would be to use Array.filter()

const myObj = {
      "notifcations": [
        {
          "title": "Joined the Tournament.",
          "description": "You have registered in the Tournament of Tournament #141, issued ₹10 from your balance.",
          "amount": 10,
          "createdAt": "2021-05-08T12:03:02.431Z",
          "expiresAt": "2021-05-08T12:03:05.983Z",
          "_id": "6277b17968729c2811137fb0"
        },
        {
          "title": "Joined the Tournament.",
          "description": "You have registered in the Tournament of Tournament #142, issued ₹10 from your balance.",
          "amount": 10,
          "createdAt": "2022-05-08T12:03:02.431Z",
          "expiresAt": "2022-05-09T12:03:05.983Z",
          "_id": "6277b17968729c2811137fb0"
        },
        {
          "title": "Joined the Tournament.",
          "description": "You have registered in the Tournament of Tournament #143, issued ₹10 from your balance.",
          "amount": 10,
          "createdAt": "2022-05-08T12:03:02.431Z",
          "expiresAt": "2022-05-09T12:03:05.983Z",
          "_id": "6277b17968729c2811137fb0"
        }
      ]
};

myObj.notifcations = myObj.notifcations.filter(a => new Date(a.expiresAt) > new Date());
console.log(myObj);

  • Related