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

问题描述 投票:0回答:2

我通过 Web UI 尝试了几次,但首先文件没有在资源管理器中显示给我,当我最终解决这个问题并上传我的 .json 时,有一个条目:

错误:“身份验证令牌已过期”

我只想导入该 .json 文件,如何做到这一点?

json database firebase firebase-realtime-database
2个回答
1
投票

身份验证令牌可能已过期,因为您在上传之前在该页面上停留的时间太长。继续尝试,只要

.json
格式正确,它就会起作用。


0
投票

我已成功通过运行使用以下软件包的 Nodejs 脚本将数据从

JSON
文件导入到 Firebase 中:

先决条件: 在运行此脚本之前,请确保以下软件包已全局安装或在您的项目中可用: 通过运行安装它们:

  • npm i firestore-export-import
  • npm i firebase-admin

套餐简短描述:

  1. firestore-export-import
    - 允许您通过子集合从 firestore 导出和导入数据;
  2. fs
    - 文件系统包,辅助文件读/写操作;
  3. path
    - 模块提供用于处理文件和目录路径的实用程序。 (我用它来通过获取
    path.sep
    来获取目录分隔符);
  4. firebase-admin
    - 允许从 Node.js 中的特权环境(例如服务器或云)访问 Firebase 服务。

这里是它实际执行的示例(删除 id 并将其作为键添加到这些对象的位置,如果对象中没有 id 则仅添加一个键):

导入后在 firebase 中的样子:

最终结果 - 代码要点.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 库,更多信息这里

此代码的部分内容取自此源 - gist.github

© www.soinside.com 2019 - 2024. All rights reserved.