LoginSignup
1
2

More than 3 years have passed since last update.

firebaseのCloud Firestoreの指定のドキュメント内の既に登録済みのフィールドを、上書きせずに新たに値を追加する場合(※ionic-vueで開発中)

Posted at

例えば
既に登録済みの、ドキュメントのidが
addedPetIdで、既に登録済みのフィールド


petProfile: { 
  petName: "ペットの名前"
}


petProfile: { 
  petName: "ペットの名前",
  petAvatar: photoUrl 
}

このような形で
petAvatar: photoUrlを新たに追加したい場合

.setを使って、下記のようにすれば追加できる。


async addPetProfileAvatar(addedPetId, photoUrl) {
    const user = this.getUser();
    return await this.db
      .collection(`users/${user.uid}/pets`)
      .doc(`${addedPetId}`)
      .set(
        {
          petProfile: { petAvatar: photoUrl },
        },
        { merge: true } // ←これが大事
      )
      .then()
      .catch(function(error) {
        console.error("Error adding document: ", error);
      });
  }

ポイントは
{ merge: true }を追加してるところ。
これは

新しいデータを既存のドキュメントに統合するオプション

だそうです。
これがないと他の値は消されて、新たに追加された値だけ入った状態で上書きされます。

参考:
https://firebase.google.com/docs/firestore/manage-data/add-data

1
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
1
2