【问题标题】:Why can i see the update succesful of a document?为什么我可以看到文档更新成功?
【发布时间】:2021-01-16 06:52:57
【问题描述】:

我想更新我的文档的状态“状态”,但是执行之后我看不到变化,这是怎么回事?

let batch = firebaseApp.firestore().batch()
schools
  .get()
  .then(snapshot => {

    snapshot.docs.forEach(doc => {
      const student = firebaseApp
        .firestore()
        .collection('students')
        .doc(doc.id)
      batch.update(student, {
        status: 'changed',
      })

      student.get().then(function(doc) {

        console.log("here", doc.data());
      })
    })
  })

在控制台我看到这个:'here' 'suscribed' 应该是 'here' 'changed'

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    首先,如果您不需要读取操作集中的任何文档,则可以将多个写入操作作为一个批处理执行,其中包含 set()、update() 或 delete() 操作的任意组合。一批写入原子完成,可以写入多个文档。

    您应该使用的批处理中的倒数第二行代码

    // Commit the batch
    batch.commit().then(function () {
        student.get().then(function(doc) {
           console.log("here", doc.data());
      })
    });
    

    batch.commit();
    

    在数据库中应用所需的更改

    【讨论】:

      【解决方案2】:

      您的代码中有几个错误:

      1. 正如 mohammad javad ahmadi 在他的回答中提到的,您没有提交您的批次,因此 student 文档没有更新。
      2. 您需要等待异步批处理操作完成才能查询student 文档以检查它们是否已更新。

      以下应该可以解决问题:

        let batch = firebaseApp.firestore().batch();
      
        const studentRefs = []; // An array of DocumentReferences
      
        schools
          .get()
          .then((snapshot) => {
            snapshot.docs.forEach((doc) => {
              const student = firebaseApp
                .firestore()
                .collection('students')
                .doc(doc.id);
      
              studentRefs.push(student);
      
              batch.update(student, {
                status: 'changed',
              });
            });
            return batch.commit();
          })
          .then(() => {
            // Here we know the batched write is completed
            // and ALL students documents were updated
            // Let's use Promise.all in order to get all the students
      
            // We use the studentRefs array that we populated in the previous then() block, in order to build an Array of Promises
      
            return Promise.all(studentRefs.map((ref) => ref.get()));
          })
          .then((snapshots) => {
            // snapshots is an Array of DocumentSnapshots 
            
            snapshots.forEach(snap => {
                console.log(snap.data());
            })
          });
      

      注意chain the promises 是如何由batch.commit()Promise.all() 返回的。

      【讨论】:

        猜你喜欢
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多