【问题标题】:How to Query through a list of documents and then update the field value in firebase?如何通过文档列表查询然后更新firebase中的字段值?
【发布时间】:2019-09-23 17:39:18
【问题描述】:

我想更改我在 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-firestore


    【解决方案1】:

    事实上,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
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 2020-10-23
      • 1970-01-01
      • 2021-12-19
      • 2021-05-22
      • 2022-01-21
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多