LoginSignup
9
3

More than 3 years have passed since last update.

【Firestore】配列へのデータの追加で Cannot read property 'arrayUnion' of undefined

Last updated at Posted at 2020-04-10

arrayUnion を使用する

test.firestore.js
var washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});

データの追加 | Firestore | Google Cloud

エラーと変更

err.bash
TypeError: Cannot read property 'arrayUnion' of undefined

arrayUnionがundefined??

def.js
const admin = require('firebase-admin')
var fireStore = admin.firestore()
fireStore
    .collection('hoge')
    .doc('fuga')
    .update({
+      regions: admin.firestore.FieldValue.arrayUnion('additional_i')
-      regions: fireStore.FieldValue.arrayUnion('additional_i')
    })

原因

(しかしこれがどうして治ったのかよくわからないので、強い人コメントで教えていただけると嬉しいです…!) と書いていたところ、@sgr-ksmt さんからコメントをいただき原因が判明しました。

admin.firestore()admin.firestore の混同

admin.firestore() と admin.firestoreの違いによるものかと思います。前者はオブジェクト、後者は型になります。
個人的には以下のようにしてこの誤用を防ぐようにすると良いかなと思っています。(typescriptの場合ですが)
@google-cloud/firestoreから参照できるFieldValueと、 admin.firestore.FieldValue は同一のものになります。

answer.js
import { FieldValue } from '@google-cloud/firestore';
import * as admin from 'firebase-admin'

admin.firestore()
    .collection('hoge')
    .doc('fuga')
    .update({
      regions: FieldValue.arrayUnion('additional_i')
    })

Qiitaコミュニティ最高ですね…

9
3
4

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
9
3