18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FirestoreにJSONを取り込む

Posted at

JSON形式で準備されたテストデータ等をFirestoreに取り込む方法。

準備

必要なモジュールのインストール

ローカルでバッチ実行を想定しているのでfirebase-adminと、本命コンポーネントのfirestore-export-importをインストール。

npm install --save firebase-admin
npm install --save firestore-export-import

秘密鍵の取得

firebase-adminの実行には秘密鍵が必要なので準備する。

ユーザーと権限 -> サービスアカウント -> 新しい秘密鍵の生成

jsonの準備

今回は下記のjsonを取り込む(参考ページよりそのまま拝借しました)。

firestore-export-importで取り込むことを想定する場合は、このような形式を意識しておく必要がある。

users.json
{
  "users": [
    {
      "id": 1,
      "first_name": "Kristin",
      "last_name": "Smith"
    },
    {
      "id": 2,
      "first_name": "Olivia",
      "last_name": "Parker"
    },
    {
      "id": 3,
      "first_name": "Jimmy",
      "last_name": "Robinson"
    },
    {
      "id": 4,
      "first_name": "Zack",
      "last_name": "Carter"
    },
    {
      "id": 5,
      "first_name": "Brad",
      "last_name": "Rayburn"
    }
  ]
}

最後の,はとったほうがいいみたい。

実装

いろいろ書いていますが、殆どはコンフィグ関連で、取り込み関連はほぼ1行。

index.js
var admin = require("firebase-admin");
var serviceAccount = require("path/to/config.json");
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://{project}.firebaseio.com"
});

var db = admin.firestore();

var fireStoreService = require('firestore-export-import');

//値を追加
// var docRef = db.collection('users').doc('0001').set({ name: 'hoge', age: 33 });

const jsonToFirestore = async () => {
    try {
        await fireStoreService.restore('./users.json');
    } catch (e) {
        console.log(e);
    }
}
jsonToFirestore();

実行

実行すると取り込まれる。doc名称として、0,1,2,3とかが使われるみたい。

node index.js

0 was successfully added to firestore!
1 was successfully added to firestore!
2 was successfully added to firestore!
3 was successfully added to firestore!
4 was successfully added to firestore!

参考

18
18
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
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?