在 FireStore 中删除(最新片段)
Deletion in FireStore (Latest Snip)
我有一个数据 Table 我想在调用 loadCheckOut 之前删除集合中的每个文档。
我怎样才能用最新的 JS 语法来做到这一点。
我正在使用 React JS,它从 getDb() 方法初始化数据库,所以像 db.collection() 这样的方法在它上面不起作用我想要一个完整的模块解决方案
const loadCheckout = async (priceId) => {
//before adding we must delete existing collection
const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
const docRef = await addDoc(
collection(db, `customers/${user.uid}/checkout_sessions`),
{
price: priceId,
success_url: window.location.origin,
cancel_url: window.location.origin,
}
);
const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
const snap = onSnapshot(
ref,
{ includeMetadataChanges: true },
async (doc) => {
var error = null,
sessionId = null;
var first = true;
doc.forEach((ele) => {
if (first) {
error = ele.data().error;
sessionId = ele.data().sessionId;
first = false;
}
});
console.log(sessionId);
if (error) {
alert(error);
}
if (sessionId) {
const stripe = await loadStripe(stripe_public_key);
stripe.redirectToCheckout({ sessionId });
}
}
);
};
这行不通:
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
deleteDoc
函数需要一个 DocumentReference
,而您的 snapshot
是一个 QuerySnapshot
。这与语法的变化关系不大,因为 snapshot.delete()
在 SDK 的 v8 和更早版本中也不起作用。
要删除查询快照中的文档,循环结果并一一删除:
snapshot.forEach((doc) => {
deleteDoc(doc.ref);
});
我有一个数据 Table
const loadCheckout = async (priceId) => {
//before adding we must delete existing collection
const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
const docRef = await addDoc(
collection(db, `customers/${user.uid}/checkout_sessions`),
{
price: priceId,
success_url: window.location.origin,
cancel_url: window.location.origin,
}
);
const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
const snap = onSnapshot(
ref,
{ includeMetadataChanges: true },
async (doc) => {
var error = null,
sessionId = null;
var first = true;
doc.forEach((ele) => {
if (first) {
error = ele.data().error;
sessionId = ele.data().sessionId;
first = false;
}
});
console.log(sessionId);
if (error) {
alert(error);
}
if (sessionId) {
const stripe = await loadStripe(stripe_public_key);
stripe.redirectToCheckout({ sessionId });
}
}
);
};
这行不通:
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
deleteDoc
函数需要一个 DocumentReference
,而您的 snapshot
是一个 QuerySnapshot
。这与语法的变化关系不大,因为 snapshot.delete()
在 SDK 的 v8 和更早版本中也不起作用。
要删除查询快照中的文档,循环结果并一一删除:
snapshot.forEach((doc) => {
deleteDoc(doc.ref);
});