Cloud Firestore subcollection syntax in Web version 9 API

I’m trying to learn Firestore Cloud 9 using a tutorial written for Web version 8. I am stuck trying to refactor what appears to be a subcollection of some sort.

The Web 8 code looks like this:

const ref = firestore.collection('users').doc(auth.currentUser.uid).collection('posts');
const query = ref.orderBy('createdAt');
const [querySnapshot] = useCollection(query);

My (failed) attempt looks something like this:

import { firestore, auth, serverTimestamp } from "@/lib/firebase";
import { collection, getDocs, orderBy, query } from "firebase/firestore";
import { useRouter } from "next/router";
import { useCollection } from "react-firebase-hooks/firestore";

const ref = collection(firestore, 'users');
const q = query(
    ref,
    where('username', '==', auth.currentUser.uid),
    orderBy('createdAt', 'desc')
);
//const newPosts = (await getDocs(q)).docs.map((doc) => doc.data());
const [querySnapshot] = useCollection(q);

I can get the first collection without issue. However grabbing the subcollection (?) via the doc(ument) isn’t something I can figure out. I’ve tried getDocs() (commented out, above) as well as getDoc() & .doc.

>Solution :

This line in the v8 and before syntax:

const ref = firestore.collection('users').doc(auth.currentUser.uid).collection('posts');

Will look like this in v9 and later:

const ref = collection(firestore, 'users', auth.currentUser.uid, 'posts');

Leave a Reply