2

Hello I would like to convert the following firebase 8 code to firebase 9 and have no clue how to do it - any help would be welcome!

This piece of code should go inside the userDoc and then fetch the collection that is insdie that document and return all of the posts that belong to that user

if (userDoc) {
    user = userDoc.data()
    const postsQuery = userDoc.ref
        .collection('posts')
        .where('published', '==', true)
        .orderBy('createdAt', 'desc')
        .limit(5)
    posts = (await postsQuery.get()).docs.map(postToJSON)
}

enter image description here

dkorsakas
  • 37
  • 6

1 Answers1

1

Firestore's documentation has examples for both V8 and V9 so you can easily compare them and modify your code. Just switch to modular tab for the new syntax. The code in question would be like:

import { collection, query, where, getDocs, orderBy, limit } from "firebase/firestore";

const q = query(collection(db, "posts"), where("published", "==", true), orderBy("createdAt", "desc"), limit(5));

const querySnapshot = await getDocs(q);

posts = querySnapshot.docs.map(postToJSON)
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Hi thanks for the super fast response! yes I looked at the documentation; the issue that i have is that the collection that I am trying to access is within another collection; so basically there is a collection called `users` (that contains user documents) and each user document has another collection called `posts` ; so the question is how i would access posts that live on a specific user document that lives with the users collection; I want to reach this place ` usrers/specic user/userspostscollection` not this `/userpostscolsection` – dkorsakas Jan 26 '22 at 18:12
  • @dkorsakas checkout [How to get a Subcollection inside a Collection in Firestore Web Version 9 (Modular)?](https://stackoverflow.com/questions/69286935/how-to-get-a-subcollection-inside-a-collection-in-firestore-web-version-9-modul?noredirect=1&lq=1) – Dharmaraj Jan 26 '22 at 18:15
  • 1
    hey thanks - this seems to be exactly what I was looking for! – dkorsakas Jan 26 '22 at 18:22