とーますメモ

Ruby on Rails / Goなどの学習メモ

ドキュメントの追加(書込)と検索(読込)

前回の記事の続き。
thoames.hatenadiary.jp

前準備

その後、プロジェクト用のディレクトリを任意の場所に作成

例)デスクトップにsampleディレクトリを作成

$ cd Desktop
$ mkdir sample

Firebase CLIの設定

$ firebase init

続く画面では、FirestoreとHosting選んで設定を続ける。(ずっとEnterで良い)

Cloud Firestoreの設定

Realtime Databaseの後継バージョンらしいが、まだベータ版。ベータ版でも問題ないならこちらを選択したほうが良いらしい。
Webの管理画面から、[Database]を選択し、データベースを作成する。
作成するには「ロックモード」か「テストモード」かを選ぶ必要があるが、ここでは「テストモード」を選択する。

index.htmlの作成

デフォルトでpublic/index.htmlが生成されているので、
中身を以下に変更。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Sample Chat</title>
</head>
<body>
  <h1>Hello world!</h1>

  <script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-firestore.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "ウェブAPIキー",
      authDomain: "プロジェクトID.firebaseapp.com",
      databaseURL: "https://プロジェクトID.firebaseio.com",
      projectId: "プロジェクトID",
      storageBucket: "プロジェクトID.appspot.com",
      messagingSenderId: "XXXXXXXXXXXXXX"
    };
    firebase.initializeApp(config);
  </script>
</body>
</html>

ちなみにデフォルトのindex.htmlで使用されている「https://www.gstatic.com/firebasejs/5.7.0/firebase.js」を使用していると
以下の警告がコンソールに表示される。

It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.

For the CDN builds, these are available in the following manner
(replace with the name of a component - i.e. auth, database, etc):

https://www.gstatic.com/firebasejs/5.0.0/firebase-.js

ガイドにも説明があるが要は
プロダクション環境だと、全てが固まっているjsを読み込むのではなく、必要なものを
個別に読み込んだほうが望ましいとのこと。
詳しくはガイド参照。

Firestoreを使ってデータの追加と検索を行う。

追加

以下の記述を内に追加

<button id="add_name">Add</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function() {
$('#add_name').on('click', function() {
  var usersCollectionRef = db.collection("users");

  usersCollectionRef.add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
  })
  .then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
  })
  .catch(function(error) {
    console.error("Error adding document: ", error);
  });
});
});
</script>

index.htmlをブラウザで表示し、「Add」ボタンをクリックすると、データがFirestoreに追加される。

ちなみに最初は以下の記述抜きでコードを書いていたが

  db.settings({
    timestampsInSnapshots: true
  });

以下のエラーが出たため、上記のコードを入れた。

The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the
following code to your app before calling any other Cloud Firestore methods:

取得

取得についての詳細は以下のqiitaを参考にすると良い。

[参考]
Firebase Cloud Firestoreの使い方 - Qiita