Insert Trigger for Embedded Objects

I’m trying to add triggers to an object which has an embedded array of documents. How can I check if a new document has been created in the array. I’m making an app in SwiftUI and I’m fairly new to mongoDB. So from the documentation it seems like I can set up a trigger for an update operation and then check for the field updated. But the documents in the array can be edited so the update operation might not always be reliable to only look for documents created and can return an object that exists but has been edited. How can I work around this? Is there something in the documents I’m missing. Any help is appreciated, Thank you in advance.

Hi @Timothy_Tati and welcome to the MongoDB community forum!!

For better understanding of the requirement, it would be helpful if you confirm if my understanding is correct.

Are you looking for a trigger operation to insert in an array field for any new element inserted and not enabling the trigger on updating the existing element of the array?

Could you also confirm the below understanding for more clarity:

Is the trigger same as Atlas Triggers? If yes, could you also share the documentation link which you are referring for creating the Atlas trigger.

  1. Also, could you share the an example scenario with an example documents.
  2. Could you help me understand the importance of Swift UI for the above scenario.

Best regards
Aasawari

Hello,

Thank you for getting back.

Sorry, There is no relevance of SwiftUI. Just wanted to establish that I was new to the web dev/backend side of things. Yes it’s an atlas trigger from the official docs https://www.mongodb.com/docs/atlas/app-services/triggers/database-triggers/

This is how the schema is set up. Every Post has a an Array of Comment Objects

 Post:  { comments: [Comments]  } // Linked Objects

And Every Comment has an array of embedded replies.

Comment:  { replies: [Reply]  } // Embedded Objects

The way the trigger is set up is that whenever the comment is updated. It runs a “newReply” function using the last element of the array. But I realised that if somebody edits their earlier reply that would count as an update operation as well, isn’t it? Needlessly running the “newReply” func on the same last element again. Currently I’m using the pre-image to compare the two but it feels too intensive for a simple task and I couldn’t find any docs where I could find such examples.

So yes is there a way to set up triggers which ONLY gets triggered if there’s
a new insert in the array( without using the doc pre-Image, if possible) and not when the array is updated.

Also if yes, will that work for all kinds of arrays irrespective of type?