【问题标题】:Firestore: How to correctly update multiple docs with a queryFirestore:如何使用查询正确更新多个文档
【发布时间】:2021-07-14 11:28:15
【问题描述】:

基于此: Can Firestore update multiple documents matching a condition, using one query?

我在下面做了,但不太确定为什么会出现此错误:doc.update 不是函数。

let db = firebase.firestore()
db.collection('posts')
  .where('uid', '==', userId)
  .get()
  .then((snapshots) => {
    snapshots.forEach((doc) =>
      doc.update({
        username: username,
      })
    )
  })

所有帖子都有一个 uid 字段,我正在尝试更改用户名。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    doc 本身并不是对文档的引用。这是一个DocumentSnapshot,它有一个属性ref,它是一个DocumentReference。试试这个:

    let db = firebase.firestore()
    db.collection('posts')
      .where('uid', '==', userId)
      .get()
      .then(async (snapshots) => {
        const updates = []
        snapshots.forEach((doc) =>
          updates.push(doc.ref.update({
            username: username,
          }))  
        )
        await Promise.all(updates)
      })
    

    您也可以使用batch write,而不是推送单独的更新承诺。

    【讨论】:

      【解决方案2】:

      更新:请参阅 Dharmaraj 提供的答案以获得更简单、直接的答案。我没有像他建议的那样考虑使用.ref 属性,这很有意义。

      另外,我的回答假设 userID 等于文档 ID,但在这种情况下实际上并非如此。当文档 ID 和用户 ID 不相等时,需要使用查询。


      querySnapshot.forEach() 函数将 "QueryDocumentSnapshot" 传递给回调,而此 QueryDocumentSnapshot 没有可用的 update() 方法。

      来自文档: "A Query refers to a Query which you can read or listen to. You can also construct refined Query objects by adding filters and ordering."
      注意规范“读”和“听”。因此,如果您想写入文档,则需要使用查询以外的其他内容。

      update() 方法可在 DocumentReference 上使用。 (如果您阅读 DocumentReference 上的快速说明,您会注意到它确实将“写入”指定为一个用例)因此,如果我们重写上面的代码以获取 DocumentReference 而不是查询,它将看起来像这样:

      let db = firebase.firestore();
      
      // grabbing the DocumentReference that has a document id equal to userID
      let userRef = db.collection('posts').doc(userID); 
      
      // update that document
      userRef.update({username: username})
      

      这里我只是使用 .doc() 方法获取 DocumentReference 并将值存储在 userRef 中。然后我可以使用.update() 更新该文档。

      我希望这会有所帮助!

      【讨论】:

      • 出现错误:prebuilt-038c95ef-26ab9a06.js?e283:188 Uncaught (in promise) FirebaseError: Requested entity was not found.
      • @DarylWong 集合中可能不存在请求的文档。无论如何,我认为 Dharmaraj 提供了一个更简单的解决方案。
      • @DarylWong 所以我现在看到您可能遇到了错误,因为文档 ID 和用户 ID 不相等。我错过了问题中提供的图像,所以我不知道它们不相等并假设它们是相等的。如果您使用自动文档 ID,那么您将无法使用 .doc(userID) 而不会出现错误。
      猜你喜欢
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2020-10-31
      • 2020-06-18
      • 2019-02-09
      • 2019-02-21
      • 2018-08-03
      相关资源
      最近更新 更多