【问题标题】:how to select a specific doc by a condition and update it flutter firestore?如何按条件选择特定文档并更新它flutter firestore?
【发布时间】:2026-01-19 09:20:20
【问题描述】:

我想更新子集合中的一个文档,我通过条件查询它

//没有为类型'Query'定义方法'update'

games.doc(invCode).collection('usersInGame').where('answer', isEqualTo : 'value')

我的尝试是获取文档

games.doc(invCode).collection('usersInGame').where('answer', isEqualTo : 'value')
  ..then((value) => value.docs.map((e) {
      games
          .doc(invCode)
          .collection('questions')
          .doc(e.id)
          .update({'answer': ''});
    }))

但它没有在 firestore 中更新任何帮助?

【问题讨论】:

  • games.doc(invCode).collection('usersInGame').where('answer', isEqualTo : 'value') 我的尝试是获取文档 games.doc(invCode).collection( 'usersInGame').where('answer', isEqualTo : 'value').get().then((value) => value.docs.map((e) { games .doc(invCode) .collection('questions ') .doc(e.id) .update({'answer': ''}); }))

标签: firebase flutter google-cloud-firestore


【解决方案1】:

第一个错误是意料之中的,因为 Firebase 不支持更新查询。见 a.o. Can Firestore update multiple documents matching a condition, using one query?

第二个代码 sn -p 从usersInGame 读取文档,然后更新questions 集合中的文档。如果您想自己更新符合您条件的文档,那就是:

games.doc(invCode).collection('usersInGame')
  .where('answer', isEqualTo : 'value')
  ..then((value) => value.docs.forEach((doc) {
      doc.reference.update({'answer': ''});
    }))

【讨论】:

    【解决方案2】:

    您必须在查询中致电get()

    试试这个:

    games
      .doc(invCode)
      .collection('usersInGame')
      .where('answer', isEqualTo: 'value')
      .get() // <-- You missed this
      .then((value) => value.docs.map((e) {
            games
              .doc(invCode)
              .collection('questions')
              .doc(e.id)
              .update({'answer': ''});
          }));
    

    【讨论】: