Laker
Laker

Reputation: 1802

Firestore (Angularfire) "merge" or reference one document in another

I have a usecase where I have a document DI in collection A with some fields. And when all the necessary fields are filled and the document is saved, I need to create a document DV in collection B.

That document DV needs to take fields from document DI, but it also has another fields.

The problem is that I need some sort of link, not just a copy of the fields. When I change the fields which are common for both of the documents, I need to see the change in both of them.

Is firestore able to do this? Or do I have to do it myself by checking for changes and updating both of them myself?

Upvotes: 1

Views: 205

Answers (1)

robsiemb
robsiemb

Reputation: 6354

Firestore, on its own, won't automatically mirror fields between two documents.

However, you have at least 3 options:

  • You could manually mirror the data -- when you write to one document, write to both. You'll want to use batched writes (or transactions) to make sure they land atomically, though.
  • You could use a cloud function firestore trigger to automatically mirror the data (with some delay, as well as additional costs for the writes, storage, and function calls -- but of course you won't have to read multiple documents to access the data). Note that ordering is not guaranteed for the triggers, however.
  • You could store a reference to the second document in a field in the first (e.g. a reference field) to point you at the second document. You would still need to do a second read to access that reference, however. See more in this answer.

Upvotes: 2

Related Questions