7
4

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】Cloud FirestoreのCRUD(作成、読み取り、更新、削除)方法

Posted at

アプリを作成している最中で、CRUD(作成、読み取り、更新、削除)方法についてはまとめておいた方がいいなと思ってブログ書きます。
JavaScript・TypeScriptでのCRUD(作成、読み取り、更新、削除)方法を書きました。

JavaScript CRUD(作成、読み取り、更新、削除)

Firebase Firestoreを使ってデータの取得、作成、更新、および削除を行う方法について説明します。FirestoreはNoSQLデータベースであり、データはコレクションとドキュメントの形式で格納されます。以下のコードスニペットはJavaScriptを使ってFirestoreに対する基本的な操作を示しています。

  1. データの取得:
import { doc, getDoc } from 'firebase/firestore';

// docの参照を作成
const docRef = doc(db, 'コレクション名', 'ドキュメントID');

// docのデータを取得
getDoc(docRef).then((documentSnapshot) => {
  if (documentSnapshot.exists()) {
    console.log('Document data:', documentSnapshot.data());
  } else {
    console.log('Document does not exist!');
  }
});
  1. データの作成:
import { addDoc, collection } from 'firebase/firestore';

// 新しいドキュメントを作成
addDoc(collection(db, 'コレクション名'), {
  キー1: '値1',
  キー2: '値2',
  // ...
}).then((docRef) => {
  console.log('Document written with ID: ', docRef.id);
}).catch((error) => {
  console.error('Error adding document: ', error);
});
  1. データの更新:
import { updateDoc } from 'firebase/firestore';

// 既存のドキュメントを更新
updateDoc(doc(db, 'コレクション名', 'ドキュメントID'), {
  キー1: '新しい値1',
  // ...
}).then(() => {
  console.log('Document successfully updated!');
}).catch((error) => {
  console.error('Error updating document: ', error);
});
  1. データの削除:
import { deleteDoc } from 'firebase/firestore';

// 既存のドキュメントを削除
deleteDoc(doc(db, 'コレクション名', 'ドキュメントID')).then(() => {
  console.log('Document successfully deleted!');
}).catch((error) => {
  console.error('Error deleting document: ', error);
});

上記のコードはFirebase Firestoreの基本的な操作を示しています。エラーハンドリングと非同期処理を含めて、データの取得、作成、更新、および削除を行うことができます。

TypeScript 取得・作成・更新・削除方法

Firebase Firestoreを使用するには、まずFirebase SDKをプロジェクトにインストールする必要があります。以下は、Firebase Firestoreを使ってデータの取得、作成、更新、削除を行うTypeScriptのコード例です。

  1. データの取得:
import { getFirestore, doc, getDoc } from 'firebase/firestore';

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function getData() {
  const docRef = doc(db, 'コレクション名', 'ドキュメントID');
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    console.log('Document data:', docSnap.data());
  } else {
    console.log('No such document!');
  }
}

getData();
  1. データの作成:
import { addDoc, collection } from 'firebase/firestore';

async function addData() {
  try {
    const docRef = await addDoc(collection(db, 'コレクション名'), {
      キー1: '値1',
      キー2: '値2',
      // ...
    });
    console.log('Document written with ID: ', docRef.id);
  } catch (e) {
    console.error('Error adding document: ', e);
  }
}

addData();
  1. データの更新:
import { updateDoc } from 'firebase/firestore';

async function updateData() {
  try {
    await updateDoc(doc(db, 'コレクション名', 'ドキュメントID'), {
      キー1: '新しい値1',
      // ...
    });
    console.log('Document successfully updated!');
  } catch (e) {
    console.error('Error updating document: ', e);
  }
}

updateData();
  1. データの削除:
import { deleteDoc } from 'firebase/firestore';

async function deleteData() {
  try {
    await deleteDoc(doc(db, 'コレクション名', 'ドキュメントID'));
    console.log('Document successfully deleted!');
  } catch (e) {
    console.error('Error deleting document: ', e);
  }
}

deleteData();

各関数は非同期(async)関数として定義され、非同期のFirestore操作はawaitキーワードを使って待機されます。エラー処理はtry/catchブロックを使って行われます。これらの関数は、Firestoreでの基本的なCRUD(作成、読み取り、更新、削除)操作を示しています。

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?