Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Firestore, can you update and add to a sub-collection using a single update call?

I see that there is an example that calls update() and updates nested fields with firestore. Can you do a similar thing that does an update and adds to a subcollection instead?

e.g. we change this example from favorites being an object hash to a subcollection

var frankDocRef = db.collection("users").doc("frank");
frankDocRef.set({
    name: "Frank",
    favorites: { food: "Pizza", color: "Blue", subject: "recess" },
    age: 12
});

to

frankDocRef.set({
    name: "Frank",
    favorites.add({ food: "Pizza"}), // I know this is probably the wrong syntax
    age: 12
});

Would I create a batched write or a transaction because it goes across a single document and a sub-collection document separately?

like image 724
MonkeyBonkey Avatar asked Jan 24 '26 12:01

MonkeyBonkey


1 Answers

Firestore doesn't offer an API to update multiple documents (no matter where they live) in a single call to set() or update() on a document reference.

You should do a batch write instead if you want to update multiple documents atomically. You only need a transaction if you need to read the value of a document before updating it (for doing things like incrementing a count).

like image 178
Doug Stevenson Avatar answered Jan 27 '26 01:01

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!