E.P
E.P

Reputation: 117

How to Query through a list of documents and then update the field value in firebase?

I would like to change the name of every state that named boston in my collection of document in firestore how can I query through the list of documents in firestore then change the current state name to the new name with react native?

I tried this

export const Save = ({ NewName }) => {

  var db = firebase.firestore()

  var batch = db.batch();

  var sfDocRef = db.collection("cities").where("state", "==", "boston");
  var sfRe = db.collection("country").doc("SF");

     return () => {

        batch.update(sfDocRef, {"state": NewName})
        batch.update(sfRe, {"state": NewName})

        batch.commit()
  }
}

but got this error

Function WriteBatch.update() requires its first argument to be a DocumentReference, but it was: a custom query object

Upvotes: 1

Views: 300

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

As a matter of facts, sfDocRef is not a DocumentReference, but a Query.

You have to execute the query with the asynchronous get() method and for each document returned by this query, add it to the batch. The following piece of code would do the trick:

var batch = db.batch();

var sfRe = db.collection("country").doc("SF");

var sfDocQuery = db.collection("cities").where("state", "==", "boston");

sfDocQuery.get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
        batch.update(doc.ref, { "state": NewName });
    });

    //......
    batch.update(sfRe, {"state": NewName});  //This one will work, since sfRe is a DocumentReference
    //......


    return batch.commit()

})
.then(() => {

    //The commit() method is asynchronous and returns a Promise

    //return for your Save function

})

Upvotes: 2

Related Questions