Last active
September 19, 2020 10:08
-
-
Save zeusbaba/1d5924a400b70565c85fcceec9bb080b to your computer and use it in GitHub Desktop.
export Firestore collection into json file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Requirements: | |
1) To be able to access your Firestore collections, you must have serviceAccountKey.json , | |
You can generate it | |
- via Firebase Project Overview -> Settings -> Service accounts | |
- Generate new private key, then download it as codementorship_serviceAccountKey.json file. | |
Put this file in the same folder as this script. | |
2) use this js file (firestore-export.js) as part of basic node.js project, | |
and with a simple package.json that contains the following deps | |
"firebase": "^3.4.0", | |
"firebase-admin": "^6.0.0", | |
Run it like this: | |
node src/firestore-export.js collectionName | |
*/ | |
const admin = require("firebase-admin"); | |
const fs = require('fs'); | |
const serviceAccount = require("./codementorship_serviceAccountKey.json"); | |
let collectionName = process.argv[2]; | |
let subCollection = process.argv[3]; | |
// FIXME You should replace databaseURL with your own | |
admin.initializeApp({ | |
credential: admin.credential.cert(serviceAccount), | |
databaseURL: "https://codementorship.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(collectionName+".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'); | |
}) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment