如何将.json文件导入Firebase数据库?

n8ghc7c1  于 4个月前  发布在  其他
关注(0)|答案(2)|浏览(60)

我通过web UI尝试了几次,但首先文件没有在资源管理器中显示给我,当我最终绕过它并上传我的.json时,有一个条目:
错误:“Auth token is expired”
我只是想导入那个.json文件,怎么做呢?

cqoc49vn

cqoc49vn1#

Auth Token可能已过期,因为您在上传它之前在页面上停留的时间太长。请继续尝试,它将正常工作,前提是.json正确。

xienkqul

xienkqul2#

我通过运行Node.js脚本成功地将数据从JSON文件导入Firebase。
Pre-requesites:在运行此脚本之前,请确保以下软件包已全局安装或在项目中可用。
我使用了以下软件包:

  • 第一个月
  • npm i firebase-admin

软件包简短描述:

  1. firestore-export-import-允许你从firestore导出和导入数据,并使用子集合;
  2. fs-文件系统包,帮助文件读/写操作;
  3. path-模块提供了处理文件和目录路径的实用程序。(我用它通过获取path.sep来获取目录分隔符);
  4. firebase-admin-允许从Node.js中的特权环境(如服务器或云)访问Firebase服务。
    您的serviceAccount.json文件[https://stackoverflow.com/questions/40799258/where-can-i-get-serviceaccountcredentials-json-for-firebase-admin]
{
  "type": "service_account",
  "project_id": "yourProject_id",
  "private_key_id": "yourPrivate_key_id",
  "private_key": "yourPrivate_key",
  "client_email": "yourClient_email",
  "client_id": "yourClient_id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/yourClient_x509_cert_url",
  "universe_domain": "googleapis.com"
}

字符串
下面是一个例子,它实际上是这样做的:它删除ID并将它们作为键添加到它们存在的对象中,或者如果对象中没有ID,则简单地添加一个键
x1c 0d1x的数据
导入后在firebase中的外观:

end result - code gist.github

// Imports
const firestoreService = require('firestore-export-import')
const serviceAccount = require('./serviceAccount.json')
const fs = require('fs')
const path = require('path')
const tempFileName = `${__dirname}${path.sep}data-temp.json`;
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

// Get a reference to the Firestore database
const db = admin.firestore();
(async() => {
  try {
    const fileContents = fs.readFileSync(`${__dirname}/src/data.json`, 'utf8');
    const data = JSON.parse(fileContents);
    const transformed = transformDataForFirestore(data);
    fs.writeFileSync(tempFileName, JSON.stringify(transformed));
    await jsonToFirestore();
    fs.unlinkSync(tempFileName);
  } catch (error) {
    console.error('Error occurred during the import process:', error);
  }
})();
async function jsonToFirestore() {
  try {
    console.log('Initialzing Firebase')
    await firestoreService.initializeFirebaseApp(serviceAccount)
    console.log('Firebase Initialized')

    await firestoreService.restore(db, tempFileName)
    console.log('Upload Success')
  } catch (error) {
    console.log(error)
  }
}

// In order to preserve ids in data.json
// as ids in firestore
// must use keyed object (id being the key) instead of array of records
function transformDataForFirestore(data) {
  const collections = { ...data
  }; // Create a shallow copy to avoid mutating the original 'data'
  delete collections.stats;

  const collectionsById = {};

  Object.keys(collections).forEach((collectionKey) => {
    collectionsById[collectionKey] = {};

    // Check if 'collection' is an array before iterating
    const collection = collections[collectionKey];
    if (Array.isArray(collection)) {
      collection.forEach((record) => {
        collectionsById[collectionKey][record.id] = { ...record
        }; // Create a copy of 'record' to avoid modifying the original object
        delete collectionsById[collectionKey][record.id].id;
      });
    } else {
      console.error(`The collection '${collectionKey}' is not an array.`);
      // Decide how to handle this scenario, whether to skip or handle differently
    }
  });

  return collectionsById;
}


可以改进的部分:

  • 使用lodash库的深度克隆,更多关于here的内容

这段代码的一部分取自这个source - gist.github

相关问题