0

Suppose I have two top-level collections, users and companies. The companies collection contains a sub collection of Users, called employees. What's the most simple way to ensure that User records in the users and companies/employees paths are synchronized? Is it more common to use batch operations or a trigger function?

GoldenJoe
  • 7,874
  • 7
  • 53
  • 92

1 Answers1

2

If your document writes are coming directly from your client app, you can use security rules to make sure that all documents have the same values as part of a batch write. If you write the rules correctly, it will force the client to make appropriate batch writes at all required locations, assuming that you have a well-defined document structure.

You can see a similar example of this technique in this other question that ensures that clients increment and decrement a document counter with each create and delete. Your rules will obviously be more complex.

Since security rules only apply to client code, there are no similar techniques for backend code. If you're writing code on the backend, you just have to make sure your code for batch writes are all correct.

I see no need to trigger a Cloud Function if you're able to do a batch write, as the batch will take effect atomically and immediately, while the function will have some latency, and possibly incur a race condition, since you don't have a guaranteed order of execution.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • What if the document writes are not coming from the client? Say for example, if I run some SaaS and only want clients I add myself using the app? Throw some javascript up as a Function and call that? – GoldenJoe Feb 20 '20 at 20:15
  • Then that's the backend case I was talking about. You can still do a batch write, but you will have to verify that your code is correct - nothing will be able to 'check' your work like security rules. – Doug Stevenson Feb 20 '20 at 20:30
  • That's a bit of a bummer, but I guess it's just a limitation of Firestore. Thanks! – GoldenJoe Feb 20 '20 at 21:32