Comment on page
Firestoreを利用する
Firebaseの初期化を
initializeApp
で行います。getFirestore
でFirestoreの初期化と参照を取得します。const firebaseConfig = {
apiKey: "******************************",
authDomain: "test.firebaseapp.com",
databaseURL: "https://test.firebaseio.com",
projectId: "test",
storageBucket: "test.appspot.com",
messagingSenderId: "**********",
appId: "1:**********:web:********************"
};
const firebase = initializeApp(firebaseConfig);
const db = getFirestore(firebase)
import {
getFirestore, collection, getDocs, addDoc, updateDoc, doc, deleteDoc, serverTimestamp,
} from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-firestore.js';
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js";
ドキュメントの新規作成は、
addDoc()
メソッドを使用します。Cloud Firestore はデータをドキュメントに保存。ドキュメントはコレクションに保存されます。
次のコードでは、users コレクションに新しいドキュメントを作成します。
users コレクションが存在しない場合は、下記処理で新規にコレクションが作成されます。
const docRef = await addDoc(collection(db, "users"), {
name: "monaca"
});
コレクションからのドキュメント読み取りは、
getDocs()
メソッドを使用します。users コレクションの全てのドキュメントを読み取っています。
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
ドキュメントの更新は、
updateDoc()
メソッドを使用します。const docRef = doc(db, "users", docRef.id);
await updateDoc(docRef, {
born: 2020
});
ドキュメントを削除するには、
deleteDoc()
メソッドを使用します。const docRef = doc(getFirestore(), "users", docRef.id);
await deleteDoc(docRef);
最終更新 1yr ago