Updating documents in Cloud Firestore based on a query
Asked Answered
P

2

6

is it possible to set values with firebase cloud function that includes a where clause?

E.g

admin.firebase.firestore().collection('Accounts').where("imagePathName", '==', docNamed).set({
  original: 'trial'
});

this is giving me an error.

Preferable answered 19/6, 2018 at 16:7 Comment(2)
This seems to have nothing to do with Cloud Functions. Did you mean Cloud Firestore?Tacnode
yes cloud firestore.Preferable
C
6

You can call set() to create or update a document represented by a DocumentReference type object.

A query doesn't have a set method. You would instead have to obtain all the documents from the Query using get() to obtain a QuerySnapshot, iterate that, then call set() on each document individually.

Countrywide answered 19/6, 2018 at 16:12 Comment(1)
Thanks for the help, much appreciated.Preferable
T
6

I just want to add this to the answer of Doug Stenvenson.

Once you get your querySnapshot with something like: admin.firestore().collection('Accounts').where("imagePathName", '==', docNamed).get();)

The following code didn't update all the documents as I would (but only one):

querySnapshot.forEach(async doc => {
  await doc.ref.update(newData);
});

What I had to do instead to make it work was:

for (const doc of querySnapshot.docs) {
  await doc.ref.update(newData);
}
Teodorateodorico answered 1/4, 2020 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.