Skip to content

Instantly share code, notes, and snippets.

@turystahobby
Forked from codediodeio/config.js
Created January 13, 2021 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turystahobby/db04a78d57dca2b17b8c360212837ccf to your computer and use it in GitHub Desktop.
Save turystahobby/db04a78d57dca2b17b8c360212837ccf 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment