LoginSignup
3
4

More than 1 year has passed since last update.

FirestoreのCollectionをExport&Importする

Last updated at Posted at 2021-12-21

はじめに

開発環境と本番環境でデータ移行する際に、FirestoreのCollectionを丸ごとExport&Importしたいと思ってスクリプトを書きました。

準備

firestore-export-importを使います。
https://www.npmjs.com/package/firestore-export-import

npm install firestore-export-import
OR
yarn add firestore-export-import

jqコマンドがなければインストール

brews install jq

Firebase コンソールでserviceAccountKey.jsonをダウンロードして、任意の場所に保存します。

Export用スクリプト

exportCollection.js
const jsons = {
  'prd': './serviceAccountKey_prd.json',  // Prd用のKey
  'dev': './serviceAccountKey_dev.json',  // Dev用のKey
};

if (process.argv.length < 4) {
  console.log(`Usage: node exportCollection.js <dev|prd> <target_collection>`)
  return -1;
}
const env = process.argv[2];
const targetCollection = process.argv[3];
if (!jsons[env]) {
  console.log(`Usage: node exportCollection.js <dev|prd> <target_collection>`)
  return -1;
}

const serviceAccount = require(jsons[env]);
const firestoreService = require('firestore-export-import');
firestoreService.initializeApp(serviceAccount);

firestoreService
  .backup(targetCollection)
  .then((data) => console.log(JSON.stringify(data, null, 2)));

jsonを整形して出力するためのシェルスクリプト

ExportCollection.sh
#!/bin/sh

cd `dirname $0`
node exportCollection $1 $2 | jq . --sort-keys
chmod +x ExportCollection.sh

使い方

$ ./ExportCollection.sh dev collectionName > collectionName.json

Import用スクリプト

importCollection.js
const jsons = {
  'prd': './serviceAccountKey_prd.json',  // Prd用のKey
  'dev': './serviceAccountKey_dev.json',  // Dev用のKey
};

if (process.argv.length < 4) {
  console.log(`Usage: node importCollection.js <dev|prd> <importDataFile>`)
  return -1;
}
const env = process.argv[2];
const importDataFile = process.argv[3];
if (!jsons[env]) {
  console.log(`Usage: node importCollection.js <dev|prd> <importDataFile>`)
  return -1;
}

const serviceAccount = require(jsons[env]);
const firestoreService = require('firestore-export-import');
firestoreService.initializeApp(serviceAccount);

firestoreService.restore(importDataFile, {
  autoParseDates: true, // timestamp → Date変換
});

何もしないけど、Export側と使い方を合わせるためのシェルスクリプト

ImportCollection.sh
#!/bin/sh

cd `dirname $0`
node importCollection $1 $2
chmod +x ImportCollection.sh

使い方

$ ./ImportCollection.sh prd collectionName.json
3
4
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
3
4