简体   繁体   English

如何在 mongoose 的到期时间之前从数组中删除整个 object?

[英]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()在这里,在通知数组中,我想删除所有过期的对象 - object 中的“expiresAt” 。就像删除所有 object 中的expiresAt < Date.now()

Notifications Array is stored in mongodb and I want to create a function for this to remove expired Notifications.通知数组存储在 mongodb 中,我想为此创建一个 function 以删除过期的通知。

Any Help Please??有什么帮助吗??

Probably the simplest method would be to use Array.filter()可能最简单的方法是使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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