プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Firebase Cloud Firestore入門

obnizのようなマイコンを使ってIoTを作成しているとデータベースがあると便利だと思う事がよくある
 
但しデータベースやサーバーを用意してとなると手間暇かかる
 
そんな時はFirebaseの「Cloud Firestore」を使うのも1つの手である
 
今回はFirebaseの登録からobnizでの使い方の初歩部分を解説する
 
 

■Firebaseとは

Googleが提供しているモバイルおよびWebアプリケーションのバックエンドサービス
 
「BaaS」サービスの位置づけで、アプリ開発においてほぼ必須となるデータベースの準備や管理をサポートしてくれる
その他にも認証機能等、多数の機能を備えたバックエンドサポートパッケージである
 
 


■Cloud Firestoreとは

Firebaseが提供しているサービスの1つでデータベースの役割をしている
 
 


■obnizとは

IoTクラウドサービスで、「obniz Board」などのデバイスでRaspberry Piよりも更に簡単にIoTが始められるサービスである
使用言語は主にJavaScript
 
「obniz Board」については下記参照
obniz Board
 
 


■Firebaseの設定

①Firebaseにログイン

Googleアカウントを使用してFirebaseにログインする
 
ログインページ
 

②プロジェクト作成

「プロジェクト追加」を押下してプロジェクトを作成する
 

③アプリを追加

作成したプロジェクトの「アプリ追加」を押下後、
ウェブアイコン(</>)を押下する
SDK追加のスクリプトをobnizのスクリプト内に追記

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-analytics.js"></script>

<script>
  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
    apiKey: "hogehoge",
    authDomain: "hoge",
    databaseURL: "fugafuga",
    projectId: "fuga",
    storageBucket: "hahaha",
    messagingSenderId: "fofofo",
    appId: "mumumu",
    measurementId: "wawawa"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script>

 

④Firebase SDKを追加

obnizのスクリプト内に下記を追記
※現状では「firebase-app.js」のスクリプトが重複するので削除しておく

<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="/__/firebase/6.2.0/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="/__/firebase/6.2.0/firebase-auth.js"></script>
  <script src="/__/firebase/6.2.0/firebase-firestore.js"></script>
</body>

 
バージョンは変化するので公式サイト参照
公式サイト

 

⑤Firebaseでデータベース作成

Firebaseのコンソール画面から「Cloud Firestore」を選択し、「データベースの作成」を押下
「本番環境モード」・「テスト環境モード」のどちらかを選択し、「コレクションを開始」を押下してデータを登録する
※「本番環境モード」はobnizで読み書きできなくなるのでセキュリティ的に問題ないのであれば「ルール」タブで下記を「true」に変更する

//変更前
allow read, write: if false;

//変更後
allow read, write: if true;

 
 


obnizでデータベースとして「Cloud Firestore」を利用する

obnizのソースに記述
 

・データ取得

db.collection("コレクション名").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        //オブジェクトを取得
        console.log(doc.data());
        //フィールドを取得
        console.log(doc.get("フィールド名"));
        });
});

 

・データ追加

var db = firebase.firestore();
db.collection("コレクション名").add({
  フィールド名: "値"
})
.then(function() {
    //成功時
    console.log("追加成功");
})
.catch(function(err) {
    //失敗時
    console.log("エラー: " + err);
});

 
 
その他詳細は公式サイト参照
Firebase公式サイト
 
obniz公式サイト