Home > database >  how to select a specific doc by a condition and update it flutter firestore?
how to select a specific doc by a condition and update it flutter firestore?

Time:11-02

i want to update a document in a sub collection where i query it by a condition

//The method 'update' isn't defined for the type 'Query'

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

my try is to get the doc

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': ''});
    }))

but it does not update in firestore any help ?

CodePudding user response:

You have to call get() on the query.

Try this:

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': ''});
      }));

CodePudding user response:

That first error is quite expected, as Firebase doesn't support update queries. See a.o. Can Firestore update multiple documents matching a condition, using one query?

The second code snippet reads documents from usersInGame and then updates documents in the questions collection. If you want to update the documents matching your condition themselves, that'd be:

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