LoginSignup
1
1

More than 3 years have passed since last update.

FireStoreにデータを投入する時に、値がundefinedのpropertyがあると怒られる

Posted at

掲題の通り。
undefinedを含むオブジェクトをaddやsetで渡すとエラーを投げる。
fireStoreのNull型に自動変換とかはしてくれないし、
そのプロパティだけ自動で省くといったような気の利いたことはしてくれない。
スキーマレスとは言っても受け入れられないものはある。

typescriptで言うところの

type HOGE = {
  fuga?:someType 
}

のようなプロパティがundefined可能性もあるオブジェクトを投入する場合は注意。
(なお、上記の場合fugaプロパティ自体が存在しなければセーフ。
fugaプロパティが存在してかつundefinedが入っているとアウト。)

対応策

  1. undefinedの場合はフィールドを消す(deleteを使う)
  2. undefinedの場合はnullに変換する(nullならfirestoreのNULL型になる)
  3. update系の場合ならfirebase.firestore.FieldValue.delete()に変換する(フィールド自体をfirestore上に残したくない場合) ただし、create処理でfirebase.firestore.FieldValue.delete()を使うとこれまたエラーを吐かれるので注意
  4. Typescriptを使った上で、そもそもundefinedをpropに持ちうるような型定義をしない
1
1
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
1