Quantcast
Viewing all articles
Browse latest Browse all 8695

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

arrayUnion を使用する

test.firestore.js
varwashingtonRef=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
constadmin=require('firebase-admin')varfireStore=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*asadminfrom'firebase-admin'admin.firestore().collection('hoge').doc('fuga').update({regions:FieldValue.arrayUnion('additional_i')})

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


Viewing all articles
Browse latest Browse all 8695

Trending Articles