Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active September 3, 2024 03:22
Show Gist options
  • Save codediodeio/513bf77ee45be6d38d27868f5345a002 to your computer and use it in GitHub Desktop.
Save codediodeio/513bf77ee45be6d38d27868f5345a002 to your computer and use it in GitHub Desktop.
Snippets from the Firestore Data Modeling Course
import * as firebase from 'firebase/app';
import 'firebase/firestore';
var firebaseConfig = {
// your firebase credentials
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const db = firebase.firestore();
import { db } from './config';
const authorId = 'dr-seuss';
const bookId = 'lorax';
// 7. Middle Man Collection
const userReviews = db.collection('reviews').where('author', '==', authorId);
const bookReviews = db.collection('reviews').where('book', '==', bookId);
// Single read with composite key
const specificReview = db.collection('reviews').doc(`${bookId}_${authorId}`);
// 8. Map
// Reviews embadded on books
const bookWithReviews = db.collection('books').doc(bookId);
const userReviews = db.collection('books').orderBy('reviews.jeff-delaney');
// 9. Array
const books = db.collection('books').where('categories', 'array-contains', 'fiction');
// 10. Bucket
// Get a collection of documents with an array of IDs
const getLikedBooks = async() => {
// Get users through book likes
const bookLikes = await db.collection('likes').doc(bookId).get();
const userIds = Object.keys( bookLikes.data() );
const userReads = userIds.map(id => db.collection('authors').doc(id).get() );
const users = await Promise.all(userReads).then(console.log);
// Get books through user likes
const userLikes = await db.collection('likes').orderBy('jeff-delaney').get();
const bookIds = userLikes.docs.map(snap => snap.id);
const bookReads = bookIds.map(id => db.collection('books').doc(id).get() );
const books = Promise.all(bookReads).then(console.log);
}
getLikedBooks()
import { db } from './config';
const authorId = 'dr-seuss';
// 4. Embedded One-to-Many
const authorWithBooks = db.collection('authors').doc(authorId)
// 5. Subcollection
const books = db.collection('authors').doc(authorId).collection('books');
// 6. Root Collection, requires index
const booksFrom1971 = db.collection('books')
.where('author', '==', authorId)
.where('published', '>', 1971);
import { db } from './config';
const userId = 'ayn-rand';
// 1. Embedded, all data contained on single document, One-to-few
const authorWithAccount = db.collection('authors').doc(userId)
// 2. Shared Document ID
const author = db.collection('authors').doc(userId)
const account = db.collection('account').doc(userId);
// 3. Join related documents with different IDs,
const getAccount = async (userId) => {
const snapshot = await db.collection('authors').doc(userId).get();
const user = snapshot.data();
return db.collection('accounts').doc(user.accountId)
}
import { db } from './config';
// Single Doc Read
const ref = db.collection('posts').doc('postId')
// Subcollection Read
const ref = db.collection('posts').doc('postId').collection('tags');
// Bucket Read
const post = db.collection('posts').doc('postId')
const tags = db.collection('tags').doc('postId')
// Multi-document read
const post = await db.collection('posts').doc('postId').get();
const tagIds = post.data().tags;
const tagReads = tagIds.map(tag => db.collection('tags').get(tag));
const tags = await Promise.all(tagReads);
// Helper: Reads an array of IDs from a collection concurrently
const readIds = async (collection, ids) => {
const reads = ids.map(id => collection.doc(id).get() );
const result = await Promise.all(reads);
return result.map(v => v.data());
}
import { db } from './config';
import * as firebase from 'firebase/app';
const remove = firebase.firestore.FieldValue.arrayRemove;
const union = firebase.firestore.FieldValue.arrayUnion;
export const follow = (followed, follower) => {
const followersRef = db.collection('followers').doc(followed);
followersRef.update({ users: union(follower) });
}
// 2. Unfollow User
export const unfollow = (followed, follower) => {
const followersRef = db.collection('followers').doc(followed);
followersRef.update({ users: remove(follower) });
}
// 3. Get posts of followers
export const getFeed = async() => {
const followedUsers = await db.collection('followers')
.where('users', 'array-contains', 'jeffd23')
.orderBy('lastPost', 'desc')
.limit(10)
.get();
const data = followedUsers.docs.map(doc => doc.data());
const posts = data.reduce((acc, cur) => acc.concat(cur.recentPosts), []);
const sortedPosts = posts.sort((a, b) => b.published - a.published)
// render sortedPosts in DOM
}
@Casal0x
Copy link

Casal0x commented Sep 16, 2022

Are you going to update to v9 syntax?

@Pranav322
Copy link

Are you going to update to v9 syntax?

is is udated? should i go for this course

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