如何查询文档列表,然后更新firebase中的字段值?

问题描述 投票:0回答:1

我想更改 firestore 文档集合中名为 boston 的每个州的名称,如何查询 firestore 中的文档列表,然后使用 React Native 将当前州名称更改为新名称?

我试过这个

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()
  }
}

但出现此错误

函数 WriteBatch.update() 要求其第一个参数是 DocumentReference,但它是:自定义查询对象

firebase react-native google-cloud-platform google-cloud-firestore
1个回答
2
投票

事实上,

sfDocRef
不是
DocumentReference
,而是
Query

您必须使用异步

get()
方法执行查询,并且对于此查询返回的每个文档,将其添加到批次中。下面的代码就可以解决这个问题:

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

})
© www.soinside.com 2019 - 2024. All rights reserved.