0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[firebase] ドキュメントの追加

Last updated at Posted at 2023-05-08

ドキュメントの追加

ドキュメントIDを指定して追加(全上書き)

App.jsx
import { db } from '../firebase';
import { doc, setDoc } from 'firebase/firestore';

const docRef = await setDoc(doc(db, "コレクション名", "ドキュメント名"), data);
    } catch (e) {
        console.error(e);
    }
  • dataはオブジェクトを格納できる
const docRef = await setDoc(doc(db, "コレクション名", "ドキュメント名"), {
            data1: "",
            data2: "",
        });

IDを指定しないで追加(全上書き)

App.jsx
import { db } from '../firebase';
import { doc, setDoc } from 'firebase/firestore';

const docRef = await setDoc(doc(db, "コレクション名"), data);
    } catch (e) {
        console.error(e);
    }
  • 該当するコレクションやドキュメントがあれば上書き、なければ新規作成される

データをネストしたい場合(全上書き)

  • 例えば「都道府県」というデータの中に「市町村区」というドキュメントを格納しその中にフィールドを作成したい場合
App.jsx
import { db } from '../firebase';
import { doc, setDoc } from 'firebase/firestore';

const docRef = await setDoc(doc(db, "都道府県", "東京", "市町村区", "新宿区"), data);
    } catch (e) {
        console.error(e);
    }
  • なおsetDocの引数は必ずdb + (コレクション + ドキュメント)となるため必ず奇数にしなければならない

データの一部を更新したい場合

App.jsx
import { db } from '../firebase';
import { doc, setDoc } from 'firebase/firestore';

const docRef = await updateDoc(doc(db, "コレクション名", "ドキュメント名"), data);
    } catch (e) {
        console.error(e);
    }
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?