我的回答深受@Geoffrey Bourne 回答的启发,但我必须修改一些内容并找出更多细节才能使其发挥作用。
首先,我将exportFirestore 上传到 Cloud Functions(生产)。当我通过这个 URL https://us-central1-<project-id>.cloudfunctions.net/exportFirestore 运行它时,我会下载一个文件,因为 Cloud Functions 是 read-only
以下代码用于一个名为fl_content 的集合,我会考虑将其扩展到多个集合
export const exportFirestore = functions.https.onRequest(async (req, res) => {
const collection = "fl_content";
const exportedData: any = {};
exportedData[collection] = {};
await admin
.firestore()
.collection(collection)
.get()
.then((snapshot) => snapshot.forEach((doc) => exportedData[collection][doc.id] = doc.data()))
.catch(console.error);
const data = JSON.stringify(exportedData);
res.setHeader('Content-disposition', 'attachment; filename=fire-export.json');
res.setHeader('Content-type', 'application/json');
res.write(data, function () {
res.end();
});
})
下载文件fire-export.json 后,将其放入functions 文件夹中。然后打开导入功能的 URL(本地)http://localhost:5001/<project-id>/us-central1/importFirestore。确保collection 变量在导出和导入中相同。
export const importFirestore = functions.https.onRequest(async (req, res) => {
const fs = require("fs");
const collection = "fl_content";
const fileName = "fire-export.json";
const exportedData: any = {};
exportedData[collection] = {};
fs.readFile(fileName, "utf8", async (err: any, data: any) => {
if (err) {
res.send(err);
functions.logger.error(err)
return;
}
const arr = JSON.parse(data);
const batch = admin.firestore().batch();
for (const i in arr) {
for (const doc in arr[i]) {
if (arr[i].hasOwnProperty(doc)) {
const ref = admin.firestore().collection(collection).doc(doc);
batch.set(ref, arr[i][doc]);
} else {
functions.logger.error("Missing:", JSON.stringify(doc, null, 2));
}
}
}
await batch
.commit()
.then(() => console.log("Import to Firestore Complete"))
.catch(console.error);
res.send("Import to Firestore Complete");
});
});