Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Last active June 13, 2018 15:48
Show Gist options
  • Save danielrobertson/513bb34133abe1eb02bedffdf506e9af to your computer and use it in GitHub Desktop.
Save danielrobertson/513bb34133abe1eb02bedffdf506e9af to your computer and use it in GitHub Desktop.
How to upload a list of JSON documents to Google Firestore. This script puts documents into a collection named "animals"
const firebase = require("firebase-admin");
const serviceAccount = require("./firebase-config.json"); // from the Firebase project overview page
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://<PROJECT_NAME>.firebaseio.com"
});
// this code could theoretically run in a Cloud Function as the back-end to a volunteer filling out a form,
// or scraping a 3rd party animal database, which will spin through the records and create entries in Firestore
// under a collection named "animals"
const db = firebase.firestore();
const data = [
{
id: "A771016",
name: "Beasley",
dob: "January 1, 2013",
sex: "m",
kennel: "033",
weight: 80,
intake_date: "March 3, 2018",
energy_level: "green",
dog_friendly: true,
cat_friendly: false,
house_trained: true,
surgery_date: "September 1, 2013",
attributes: [ "EA", "ER" ],
notes: "All around good doggo",
photo_urls: [
"http://petharbor.com/get_image.asp?RES=Detail&ID=A769824&LOCATION=ASTN"
],
profile_active: true
},
{
id: "A770990",
name: "McKenzie",
dob: "January 30, 2015",
sex: "f",
kennel: "440",
weight: 70,
intake_date: "March 3, 2018",
energy_level: "blue",
dog_friendly: true,
cat_friendly: false,
house_trained: true,
surgery_date: "November 1, 2013",
attributes: ["EA", "ER"],
notes: "Fetches ball like no other",
photo_urls: [
"http://petharbor.com/get_image.asp?RES=Detail&ID=A770990&LOCATION=ASTN"
],
profile_active: true
}
];
data.forEach(doc => {
db
.collection("animals")
.doc(doc.id)
.set(doc)
.then(res => {
console.log("Document successfully written!");
})
.catch(error => {
console.error("Error writing document: ", error);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment