> For the complete documentation index, see [llms.txt](https://ja.docs.monaca.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ja.docs.monaca.io/migration-guide/nifcloud/sukuriputo/sanpuru1getsanpuru.md).

# サンプル1（GETサンプル）

NCMB (ニフクラ mobile backend) のGETメソッドのサンプルを、Firebase FunctionsとFirebase Firestoreを使って実装する方法について解説しています。

{% embed url="<https://mbaas.nifcloud.com/doc/current/script/sample_javascript.html#GET%20%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB>" %}

## **概要**

* NCMBのGETメソッドのサンプルをFirebaseで再現。
* Firestoreの `Item` コレクションからデータを取得し、ランダムに選択されたレコードを返す。

## **Firebase Functionsのコード**

* `get_random` 関数を定義して、Firestoreから `Item` コレクションのデータを取得。
* 取得したデータの中からランダムに1つのドキュメントを選択し、そのデータを返す。
* コード例:

  ```javascript
  const get_random = functions.https.onCall(async (data, context) => {
    const db = admin.firestore();
    const ref = db.collection('Item');
    const snapshot = await ref.get();
    if (snapshot.empty) {
      return null;
    }
    const docIds = snapshot.docs.map(doc => doc.id);
    const randomIndex = Math.floor(Math.random() * docIds.length);
    const randomDocId = docIds[randomIndex];
    const docSnapshot = await ref.doc(randomDocId).get();
    return docSnapshot.data();
  });

  exports.get_random = get_random;
  ```

***

## **アプリ側のコード**

* Firebase Functionsで定義した `get_random` 関数をアプリから呼び出す。
* 結果をコンソールに表示し、エラーがあればハンドリングする。
* コード例:

  ```javascript
      const get_random = httpsCallable(functions, 'get_random');
      get_random().then((result) => {
          // 結果の表示
          log(result.data);
      }).catch((error) => {
          // エラーのハンドリング
          log('Error');
          log(error);
      });
  ```

## 解説

* `result.data` は単純なJSONオブジェクトです。NCMBと異なり、ドキュメントのIDは含まれていません。ドキュメントのIDを結果に含めたい場合は、サーバー側のコードを以下のように変更する必要があります:

  ```javascript
  return {
    id: randomDocId,
    ...docSnapshot.data()
  };
  ```
* Firebase Functionsの `error` オブジェクトは、NCMBのものと異なるので注意が必要です。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://ja.docs.monaca.io/migration-guide/nifcloud/sukuriputo/sanpuru1getsanpuru.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
