0
2

More than 3 years have passed since last update.

【Swift】Cloud Firestoreのmap型で指定したプロパティのみを更新する

Last updated at Posted at 2021-02-17

はじめに

前回の投稿でもFirestoreのmap型について書いたんですが、
今回はアプリからFirestoreのmap型データの指定項目のみを更新する方法について、備考録として書きました。

■ 前回の投稿
【Swift】Cloud Firestoreでmap型を取得するTips

動作環境

Xcode12.4 / iOS14.4

Firestoreのデータ構造

Firestore内で定義したデータ構造は以下になります。
FirestoreData.png

今回の目的

map型の1つの単位は、idpriceまでになりますが、今回は一番上のデータ(1)のisOrderComplete: Bool指定してそれだけを更新します。

実装

ソースコード

func updateOrderComplete(flag: Bool, completion: @escaping (_ succsess: Bool, _ _error: Error?) -> Void) {
        // まずは、更新対象のコレクションとドキュメントを指定
        let orderRef = db.collection("ordering").document("01")
        // map型の更新したいプロパティを[key].[property]という形式で指定する(詳細は解説に記載)
        orderRef.updateData(["1.isOrderComplete" : flag]) { _error in
            if let error = _error {
                // 失敗
                completion(false, error)
            } else {
                // 成功
                completion(true, nil)
            }
        }
    }

解説

本題の解説の前に、Firestoreのmap型の構造を理解する必要があります。

KEY Value
今回は「1」に該当する部分 更新対象のisOrderCompleteを含め、
idpriceが格納されている部分

map型の構造はこのような感じです。

今回のケースでは、1(KEY)isOrderCompleteを更新することが目的です。
map型の指定したプロパティを更新したい場合、Keyとプロパティの間をドットで区切って指定することで実現できるようです。

以下、公式リファレンスを貼っておきます!
https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ja#update_fields_in_nested_objects

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2