# Firestoreを利用する

### 事前準備

Firebaseの初期化を`initializeApp` で行います。

下記の`firebaseConfig`の値は、Firebase 上のWeb アプリの[firebaseConfig](https://support.google.com/firebase/answer/7015592)にあります。

`getFirestore`でFirestoreの初期化と参照を取得します。

```javascript
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)
```

### ライブラリのインポート

Firebaseの JavaScript SDKのライブラリをCDN（コンテンツ配信ネットワーク）からプロジェクトに追加します。他のインポートについては、[こちら](https://firebase.google.com/docs/web/alt-setup)をご確認ください。

```javascript
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 はデータをドキュメントに保存。ドキュメントはコレクションに保存されます。&#x20;

次のコードでは、users コレクションに新しいドキュメントを作成します。

users コレクションが存在しない場合は、下記処理で新規にコレクションが作成されます。

```javascript
const docRef = await addDoc(collection(db, "users"), {
    name: "monaca"
});
```

### 読み取り

コレクションからのドキュメント読み取りは、`getDocs()`メソッドを使用します。

users コレクションの全てのドキュメントを読み取っています。

```javascript
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => ${doc.data()}`);
});
```

### 更新

ドキュメントの更新は、`updateDoc()`メソッドを使用します。

```javascript
const docRef = doc(db, "users", docRef.id);
await updateDoc(docRef, {
    born: 2020
});
```

### 削除

ドキュメントを削除するには、 `deleteDoc()`メソッドを使用します。

```javascript
const docRef = doc(getFirestore(), "users", docRef.id);
await deleteDoc(docRef);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ja.docs.monaca.io/sampleapp/firestorewosuru.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
