简体   繁体   中英

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

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??

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM