This repository has been archived by the owner on Jan 15, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
export.js
63 lines (55 loc) · 1.7 KB
/
export.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const admin = require("firebase-admin");
const fs = require('fs');
const serviceAccount = require("./serviceAccountKey.json");
let collectionName = process.argv[2];
let subCollection = process.argv[3];
// You should replace databaseURL with your own
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://ionic-firestore-dn.firebaseio.com"
});
let db = admin.firestore();
db.settings({ timestampsInSnapshots: true });
let data = {};
data[collectionName] = {};
let results = db.collection(collectionName)
.get()
.then(snapshot => {
snapshot.forEach(doc => {
data[collectionName][doc.id] = doc.data();
})
return data;
})
.catch(error => {
console.log(error);
})
results.then(dt => {
getSubCollection(dt).then(() => {
// Write collection to JSON file
fs.writeFile("firestore-export.json", JSON.stringify(data), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
})
})
async function getSubCollection(dt){
for (let [key, value] of Object.entries([dt[collectionName]][0])){
if(subCollection !== undefined){
data[collectionName][key]['subCollection'] = {};
await addSubCollection(key, data[collectionName][key]['subCollection']);
}
}
}
function addSubCollection(key, subData){
return new Promise(resolve => {
db.collection(collectionName).doc(key).collection(subCollection).get()
.then(snapshot => {
snapshot.forEach(subDoc => {
subData[subDoc.id] = subDoc.data();
resolve('Added data');
})
})
})
}