Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading