這是我在這里嘗試完成的基本前提。如果用戶詢問有關產品的問題,我想向當前擁有該產品的其他用戶發送通知。基本上是說“嘿,誰誰對這個產品有疑問。也許你可以提供幫助,因為你已經擁有它了”
每個 userProfile 集合都有一個名為“notify”的子集合,其中存盤了各種通知。我需要做的是對 userProducts 進行排序并找到擁有該產品的每個用戶,然后僅在擁有該產品的特定用戶的通知子集合中創建一個通知帖子。
這是基本代碼。第一點起作用,因為它確實回傳擁有該產品的用戶 ID 陣列。我現在正在努力讓它在 Notify 子集合中為那些特定用戶創建一個新檔案。這有可能嗎?
exports.Questions = functions.firestore
.document("/userPost/{id}")
.onCreate(async (snap, context) => {
const data = snap.data();
if (data.question == true) {
const userProducts = await db
.collection("userProducts")
.where("product", "==", data.tag)
.get();
const userData = userProducts.docs.map((doc) => doc.data().userId);
await db
.collection("userProfile")
.where("userId", "in", userData)
.get()
.then((querySnapshot) => {
return querySnapshot.docs.ref.collection("notify").add({
message: "a user has asked about a product you own",
});
});
});
uj5u.com熱心網友回復:
您當前的解決方案走在正確的軌道上,但可以進行改進。
- 使用保護模式進行
data.question == true檢查。 - 您不需要獲取,
userProfile/<uid>因為您沒有使用其內容。 - 一次更改多個檔案時,您應該考慮將它們一起批處理以進行更簡單的錯誤處理。
ref.add(data)是ref.doc().set(data)您可以在批量寫入中使用以創建新檔案的簡寫。
exports.Questions = functions.firestore
.document("/userPost/{id}")
.onCreate(async (snap, context) => {
const data = snap.data();
if (!data.question) {
console.log("New post not a question. Ignored.")
return;
}
const userProducts = await db
.collection("userProducts")
.where("product", "==", data.tag)
.get();
const userIds = userProducts.docs.map(doc => doc.get("userId")); // more efficient than doc.data().userId
// WARNING: Limited to 500 writes at once.
// If handling more than 500 entries, split into groups.
const batch = db.batch();
const notificationContent = {
message: "a user has asked about a product you own",
};
userIds.forEach(uid => {
// creates a ref to a new document under "userProfile/<uid>/notify"
const notifyDocRef = db.collection(`userProfile/${uid}/notify`).doc();
batch.set(notifyDocRef, notificationContent);
});
await batch.commit(); // write changes to Firestore
});
注意:對于之前沒有人購買過產品的情況,這里沒有特殊處理。也考慮 ping 產品的所有者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380459.html
標籤:javascript 火力基地 谷歌云firestore 谷歌云功能
上一篇:我無法將firebase中的計劃升級為blaze計劃
下一篇:顫振 火力 條紋
