LoginSignup
0
0

More than 3 years have passed since last update.

firebase-admin を用いて最も単純な Firebase Cloud Firestore のデータを取得するコードサンプル

Posted at

動機

Firestore のデータを取得する単純な事例があまり見当たらず、本家の資料を見てもいまいちピンとこなかったので、firebase-admin を使った最も単純なコードを書きたくなったため。

実行環境と利用ツール

Cloud Firestore 設定

まずはじめに Firebase コンソール(Web)から books コレクションと自動 ID を割り振ったドキュメントを作成します。

内容は極めて単純にしたかったので string 型の title というフィールドのみ追加します。

最後、値は javascript としています。

完成形の画面のスナップショットを貼っておきます。

Firestore data m.png

コレクション内のドキュメントを取得する最も単純なコード


// Ref : https://www.freecodecamp.org/news/the-firestore-tutorial-for-2020-learn-by-example/

const admin = require('firebase-admin');

const serviceAccount = require('./firestore-data-modeling-96db0-firebase-adminsdk-n3i63-0670471cc1.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

const booksRef = db.collection('books');

// console.log(booksRef.get());

booksRef
  .get()
  .then((snapshot) => {
    const data = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    }));
    console.log(data); 
    // [ { id: 'FY7PJJTw7EsS8x2hYphv', title: 'javascript' } ]
  });

実行結果

コード中にも記載がありますが JSON オブジェクトの配列を返します。

$ node books.js
[
  { id: 'FY7PJJTw7EsS8x2hYphv', title: 'javascript' }
]

参考資料

The JavaScript + Firestore Tutorial for 2020: Learn by Example

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0