lifecycles
lifecycles

Reputation: 142

Firebase V9, add subcollection to existing doc

const q = getDoc(doc(db, "customers", user.uid));

Hello, this returns a promise in the console.log. I have a customers collection and each user.uid is a document inside it. I want to create a subcollection for each user.uid document, so I can put an object { with some parameters} inside. But how do I create a subcollection called "checkout_sessions" for each document(user.uid). Any help would be appreciated, please, thanks

This is how its done in Firebase v8. by the time of writing the lines the firestore doesnt have a collection called checkout_sessions and this seems to create 1 for each user.uid

const docRef = await db
.collection("customers")
.doc(user.uid)
.collection("checkout_sessions").
add({
 price: priceId,
 and: two,
 more: pairs,
});

I need to create this same subcollection "checkout_sessions" and add data inside in firebase v9, please thank you!!!!!

Upvotes: 11

Views: 8462

Answers (2)

Ayyappa Vemulkar
Ayyappa Vemulkar

Reputation: 111

Just following up on Frank's answer. If you'd like to use setDoc to set a specific id -

const docRef = doc(db, "customers", user.uid, "checkout_sessions", "custom id");
setDoc(docRef, {
    price: priceId,
    and: two,
    more: pairs,
 });

Upvotes: 11

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

Rewriting code to v9 is typically a matter of changing the method calls to the equivalent function calls, and passing in the object as the first parameter.

In your code snippet that'd be:

const docRef = doc(db, "customers", user.uid);
const colRef = collection(docRef, "checkout_sessions")
addDoc(colRef, {
 price: priceId,
 and: two,
 more: pairs,
});

Upvotes: 33

Related Questions