🙆‍♀️

(動作確認済み)[ts/js]firestoreでfieldの配列に新しい値を追加する方法

2023/02/01に公開

表題の件についてChatGPTに聞いたら教えてくれた答えが有用だったので共有(一部、reactの環境で動くように修正して動作確認済み)

質問

私> how can I use ArrayUnion with update function? tell me with a concrete example of a docment

以下回答

To use the ArrayUnion operator with the update function, you need to pass an object to the update method of the document reference that contains the field to be updated with the ArrayUnion operator. The ArrayUnion operator allows you to append new elements to an array field in a document without overwriting existing elements.

Here is an example of using ArrayUnion with the update function in TypeScript:

+ import { updateDoc, arrayUnion } from '@firebase/firestore'
const updateDocWithArrayUnion = async (docRef: FirebaseFirestore.DocumentReference, field: string, value: any) => {
  try {
+    await updateDoc(docRef, {
+      [field]: arrayUnion(value)
-    await docRef.update({
-      [field]: firebase.firestore.FieldValue.arrayUnion(value)
    });
    console.log('Document updated successfully');
  } catch (error) {
    console.error('Error updating document: ', error);
  }
};

In this example, docRef is a document reference, field is a string representing the name of the field to be updated, and value is the value to be added to the array. The function updates the document by appending value to the field array.

For example, suppose you have a document with the following data:

{
  name: 'John Doe',
  interests: ['reading', 'hiking']
}

You can use the updateDocWithArrayUnion function to add a new interest to the interests array as follows:

+ import { doc } from '@firebase/firestore'
+const docRef = doc('users/123');
-const docRef = firebase.firestore().doc('users/123');
updateDocWithArrayUnion(docRef, 'interests', 'baking');

After the update, the document will contain the following data:

{
  name: 'John Doe',
  interests: ['reading', 'hiking', 'baking']
}

Discussion