Cloud Firestore で collection の基本操作

Cloud Firestore使ったときのメモ
検証用のメモだからダブルクウォートとシングルクウォートが混ざってるのは気にするな

Create

const docRef = await addDoc(collection(db, "collection"), {
  title: "title",
  description: "description",
  created_at: new Date(),
});
console.log("Document written with ID: ", docRef.id);

Read

// 単一の取得
const ref = doc(db, "collection", "document ID");
const snap = await getDoc(ref);
console.log(snap.data());

// 複数取得
const q = query(collection(db, "collection", where('title', '==', 'title')));
const snap = await getDocs(q);
snap.forEach((doc) => console.log(doc.data()));

// 順番と件数を指定して複数取得
const q = query(collection(db, "collection"), orderBy('created_at', 'desc'), limit(2));
const snap = await getDocs(q);
snap.forEach((doc) => console.log(doc.data()));

Update

const ref = doc(db, "collection", "document ID");
await updateDoc(ref, {
    title: "update title",
});

Delete

await deleteDoc(doc(db, 'collection', 'document ID'))

参考

firebase.google.com