Skip to content

Instantly share code, notes, and snippets.

@Hunter87ff
Created December 25, 2024 14:44
Show Gist options
  • Select an option

  • Save Hunter87ff/fb51b7a62f4450696ba52c701b3f43d3 to your computer and use it in GitHub Desktop.

Select an option

Save Hunter87ff/fb51b7a62f4450696ba52c701b3f43d3 to your computer and use it in GitHub Desktop.
Firebase Firestore x ExpressJS
import { initializeApp } from "firebase/app";
import e from "express";
import {getDocs, getDoc, doc, setDoc, collection, getFirestore, query, where} from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// express app init
const app = e();
// Initialize Firebase
const fs_app = initializeApp(firebaseConfig);
const db = getFirestore(fs_app);
const users = collection(db, "users");
app.get("/:name", async (req, res) => {
const _name = req.params.name;
const q = query(users, where("name", "==", _name)); //creates a query to get all the docs
const _data = await getDocs(q); //gets all the docs
const _resp = _data.docs.map(doc => doc.data()); //maps the docs to get the data
res.send(_resp.length>0?_resp[0]:{}); //sends the first data if it exists else sends an empty object
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment