• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

402
Views
Firebase - Create subcollection only if the parent doc exists

In Firestore, when you are deleting a doc, you can specify a condition like { exists: true }, in order to avoid deleting the document if it doesn't exist.

In a concurrent scenario, it is possible that we would only like to add a doc to a subcollection if the parent document exists.

For example, imagine the following NoSql structure:

   -comment (doc)
       /likes (subcollection created when the first like is given)
          -like1
          -like2
          ...

Is it possible to do something like

likeRef.create(data, { parent_exists: true });

??

Is the only way to handle this situation with Transactions (reading the parent doc, and throwing an error when .exists() is false)?

I am afraid of this type of situation because if the sub-collection is created at the same time as the container document is deleted, there could be orphan "entities" in the database that may even break the UI if it is not prepared for these extreme cases.

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is not possible as a single operation in Firestore.

The only way to do this is to start a transaction, then get() the parent document inside the transaction, and add the documents to the subcollection if the parent exists.

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error