![](/img/trans.png)
[英]How to write data to a subcollection of Firestore in v9 react JS
[英]How to get auto-generated ID of newly created document in a subcollection in Firestore Web V9? Javascript/React
onClick 我在一個包含用戶文檔的子集合中創建一個新文檔。
這是那個函數:
// Create a new checkout session in the subcollection inside this users document
const createCheckoutSession = async () => {
const collectionRef = collection(db, 'users', currentUser.uid, 'checkout_sessions');
const payload = {
price: 'price_1JvjWLChfN4TVWbYw2LdDXZZ',
success_url: window.location.origin,
cancel_url: window.location.origin
};
await addDoc(collectionRef, payload);
// TODO – Get the newly created document's id.
};
我的目標是獲取新創建的文檔的 ID。 然后在該文檔中獲取一個字段以觸發重定向到 Stripe 結帳。
在 Firestore Web V8 中,我很確定我會使用:
collectionRef.onSnapshot(async (snap) => {
const { sessionId } = snap.data();
if (sessionId) {
// We have a session, let's redirect to Checkout
// Init Stripe
const stripe = await getStripe();
stripe.redirectToCheckout({ sessionId });
}
});
如何將新創建的文檔的 ID 列表作為上面的// TODO
?
addDoc
函數向新添加的文檔返回一個Promise<DocumentReference>
。 所以你可以通過以下方式獲取 ID:
const docRef = await addDoc(collectionRef, payload);
console.log(docRef.id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.