Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating documents in Cloud Firestore based on a query

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.

like image 915
Yushin Avatar asked Jun 19 '18 16:06

Yushin


People also ask

Is there any way to update a specific index from the array in firestore?

Is there any way to update a specific index from the array in Firestore? No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.

How do I get latest documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

What does onSnapshot do?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.


2 Answers

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.

like image 132
Doug Stevenson Avatar answered Nov 14 '22 21:11

Doug Stevenson


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);
}
like image 43
Simon Avatar answered Nov 14 '22 21:11

Simon