I'm implementing a notifications system, where I have a notifications
collection with the following schema:
{
user_id: Number,
message: String,
count: Number,
timestamp: Date
}
Whenever there are 2 or more consecutive notifications for the same user with the same message
, I want to prevent storing all of them. Instead, I just want to increment count
by 1.
Here is the node.js code that handles inserting new notifications with the approach described above:
async function createNotification(user_id, message) {
const notifications = db.collection('notifications');
const [lastNotification] = await notifications.find({ user_id })
.sort({ timestamp: -1 }).limit(1).toArray();
if(lastNotifcation?.message === message) {
await notifications.updateOne(
{ _id: lastNotifcation._id },
{ count: lastNotifcation.count+1 },
)
} else {
await notifications.insertOne({ user_id, message, count: 1, timestamp: new Date() });
}
}
While the code above works, it is not atomic (it isn't a single operation). How can I achieve the logic above with one operation instead of two?