How to delete objects from `notifications` array after certain amount of time in mongoDB?

const addToNotifications = await db.collection("notifications").findOneAndUpdate(
{ author: body.author },
{
$addToSet: {
notifications: {
comment: body.comment,
notifier: body.commenter,
postId: body.postId,
notificationType: "comment",
isSeen: false,
createdAt: new Date(),
},
},

},
{ returnDocument: "after" }
);
const removeFromNotifications = await db.collection("notifications").findOneAndUpdate(
{ author: body.author },
{
$pull: {
notifications: {
isSeen: true,
createdAt: { $lt: new Date(Date.now() - 1 * 60 * 1000) }, // Older than 1 day
},
},
},
{ returnDocument: "after" }
);
const addToNotifications = await db.collection("notifications").findOneAndUpdate(
{ author: body.author },
{
$addToSet: {
notifications: {
comment: body.comment,
notifier: body.commenter,
postId: body.postId,
notificationType: "comment",
isSeen: false,
createdAt: new Date(),
},
},

},
{ returnDocument: "after" }
);
const removeFromNotifications = await db.collection("notifications").findOneAndUpdate(
{ author: body.author },
{
$pull: {
notifications: {
isSeen: true,
createdAt: { $lt: new Date(Date.now() - 1 * 60 * 1000) }, // Older than 1 day
},
},
},
{ returnDocument: "after" }
);
Or somebody tell me a better approach
3 Replies
glutonium
glutonium3w ago
maybe look at "mongodb TTL"
i_lost_to_loba_kreygasm
TTL deletes the whole document I dont want that
glutonium
glutonium3w ago
what if you have notifications as it's own document additionally with an author id

Did you find this page helpful?