Conditional Database Trigger on collection A based on a document's field value in collection B

I have a Database trigger that runs a function when a new document in collection A is added or updated, and it works fine. Is there a way to fire the trigger only if a field in my other collection B has a specific value?

An example of what I am trying to do is to fire a trigger when a user document in my USERS collection is added or updated, but only if a store document in my STORES collection has a value of true for “open” field. Let’s assume that I have to keep USERS and STORES as two separate collections!

Hi Akbar, welcome to the forum!

When creating a database trigger, you can provide a match pattern that filters the change, but it will only have visibility of the USERS document. I haven’t tested to see whether you could include a $lookup in that statement to check on a different collection.

I’d tackle this in one of two ways:

  1. Accept that the trigger will run on every change to a USERS document. The first thing the function would do is check the STORES collection to see whether it needs to make any changes or just return. Realm functions are designed to be lightweight and so this wouldn’t typically be too inefficient.
  2. Add some additional data to the USERS document, and then maintain that (possibly through another database trigger) when the STORES collection is modified.
2 Likes

Hi Andrew,
I actually originally took the 1st route that you suggested, but then I realized that the condition on the other collection is not met most of the times and so the trigger would get fired every time, but the function would not run half the times or more and so that’s too many unnecessary triggers.

I think I am going to take a variation of the second route that you suggested. It seems to be a more efficient way for my case.

Thanks for the help.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.