Caleb Robinson
Caleb Robinson

Reputation: 1120

Firebase Update with Where Clause

I'm working on a flutter app. I would like to do the equivalent of an SQL Update with a Where Clause. This is my current working solution:

Future<void> updateWhere(String valueForWhere, String valueToUpdate) async {
  try {
    List<ObjectToUpdate> items;
    var query = await Firestore.instance.collection('CollectionName')
      .where(ObjectToUpdate.field1, isEqualTo: valueForWhere)
      .getDocuments();

    if (query.documents.isEmpty)
      return;
    else {
      items = query.documents.map((item) => ObjectToUpdate.deserialize(item.data, item.documentID)).toList();
    }

    for(var item in items) {
      item.field2 = valueToUpdate;
      Firestore.instance.collection('CollectionName')
        .document(item.uid)
        .updateData(item.serialize());
    }
  } 
  catch (e) {
    print(e);
  }
}

This feels very roundabout as I have to deserialize, modify, serialize, and update each object individually.

Is there a simpler, more efficient way to do this? Or maybe some way I can optimize my current solution?

Upvotes: 1

Views: 2267

Answers (2)

Thrivikram G R
Thrivikram G R

Reputation: 1

  1. Use "where" clause to fetch the documents you wish to update.
  2. Get the document ID of each document you fetched.
  3. Now, use the same document IDs to update the corresponding documents with new data.

This does the same job as "where - update", but in two separate steps.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317372

No, you're doing the right thing. Firestore offers no equivalent of "update where" that you find in SQL.

Upvotes: 1

Related Questions