Skip to content

Instantly share code, notes, and snippets.

@SunKing2
Last active August 27, 2023 04:44
Show Gist options
  • Save SunKing2/ee8b9d27a504af25e061d664549910f6 to your computer and use it in GitHub Desktop.
Save SunKing2/ee8b9d27a504af25e061d664549910f6 to your computer and use it in GitHub Desktop.
Reading Firestore Firebase collection 2023 with javascript using bun run index.js

Reading a Firebase Firestore collection with JavaScript

Create file in current directory called index.js

Do yourself a favor, and instal Bun (a replacement for NodeJS) and run it with Bun

import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs, addDoc } from 'firebase/firestore/lite';




const firebaseConfig = {

// INSERT YOUR OWN 7 lines here  !!!!   :)

};







// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Get a list of recipes from your database
async function getRecipes(db) {
  const recipesCol = collection(db, 'recipes');
  const recipeSnapshot = await getDocs(recipesCol);
  const recipeList = recipeSnapshot.docs.map(doc => doc.data());
  return recipeList;
}

function show_recipes(recipes) {
    console.log("show_recipes");
    if (!recipes || recipes.length == 0) {
        console.log("no recipes");
        return;
    }
    // iterate thru recipes, spew name, title
    for (const recipe of recipes) {
        console.log(recipe.author, recipe.title);
    }
    console.log("done with show_recipes");
}

getRecipes(db).then((recipes) => {
    show_recipes(recipes);
    });

async function addRecipe(db, recipe) {
    const recipesCol = collection(db, 'recipes');
    const recipeSnapshot = await addDoc(recipesCol, recipe);
    return recipeSnapshot;
  }

// random integer 100 to 999:
const rrrrr =  Math.floor(Math.random() * 900) + 100;
const myRandString = rrrrr.toString();

const newRecipe = {
    author: "tom" + myRandString,
    title: "spaghetti and meatballs " + myRandString
};

addRecipe(db, newRecipe).then((recipe) => {
    console.log("... created");
    console.log(recipe.author, recipe.title);
    console.log(" done with created. for ", myRandString);
    });

async function addAndShowRecipe(db, newRecipe) {
    await addRecipe(db, newRecipe);
    const recipes = await getRecipes(db);
    show_recipes(recipes);
}

addAndShowRecipe(db, newRecipe).then(() => {
    console.log("Done adding and showing recipe for ", myRandString);
});

Now run it using a decent node.js replacement... bun

bun run index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment