# サンプル3（DELETEサンプル）

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

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

## 概要

* **目的**: NCMBでのDELETEメソッドを使用したデータ削除のサンプルを、Firebase FunctionsとFirestoreを用いて実装。
* **動作**: Firestoreの `Item` コレクションから指定されたIDのドキュメントを削除。

## Firebase Functionsのコード

### **機能**

* **データ削除**: 指定されたIDのドキュメントをFirestoreから削除。

### **コード例**

```javascript
const delete_data = functions.https.onCall(async (data, context) => {
  const body = data.body; 
  const id = body.id; // 削除するID
  return admin.firestore().collection('Item').doc(id).delete()
    .then(_ => {
      return { message: `Document ${id} successfully deleted` };
    })
    .catch(error => {
      throw new functions.https.HttpsError('internal', `Error deleting document: ${error}`);
    });
};
```

### **解説**

* **IDによる削除**:&#x20;
  * `body.id` で指定されたIDのドキュメントを削除します。
* **セキュリティ**:&#x20;
  * このサンプルではユーザー認証を行っていないため、IDがわかれば誰でも削除可能です。POSTサンプルでの認証チェックのようなセキュリティ対策を講じるか、Firebaseのルールを設定して不正な操作を防ぐことが推奨されます。

***

## アプリ側のコード

### **機能**

* 指定したIDのドキュメントを削除する `delete_data` 関数を呼び出し。

### **コード例**

```javascript
    const deleteId = document.querySelector('#deleteId').value;
    log(`${deleteId}`);
    const delete_data = httpsCallable(functions, 'delete_data');
    delete_data({
      'body' : {
        'id': deleteId
      }
    }).then((result) => {
      log(result.data);
    }).catch((error) => {
      log(error);
    });
  });
```

### **解説**

* **ドキュメントIDの指定**:
  * `body.id` に削除したいドキュメントのIDを指定し、Firebase Functionsの `delete_data` 関数を呼び出して削除を実行します。


---

# 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/migration-guide/nifcloud/sukuriputo/sanpuru3deletesanpuru.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.
