![](/img/trans.png)
[英]Accessing nested array of documents containing collections with Firebase v9
[英]Update documents in firebase V9
我正在嘗試更新 firebare 中的消息(上下文:聊天功能),例如以下方法。
markConversationAsSeen(conversationId: string, email: string) {
const messages = collection(this.firestore, 'messages');
const q = query(messages,
where('conversationId', '==' ,conversationId),
where('to', '==' , email),
where('seen', '==', false)
);
getDocs(q).then((documents) => {documents.forEach(document => {
const docId = document.id;
const ref = doc(this.firestore, `messages/${docId}`)
updateDoc(ref, { seen: true }).then();
})});
}
我認為這不是我所做的最佳選擇! 特別是因為該方法首先查找消息,然后一條一條地更新它們(對 firebase 的多次請求)
有什么建議可以增強它嗎?
謝謝 !
可能添加異步功能可以提高性能,如下所示:
import { collection, query, where, getDocs, updateDoc, doc } from "firebase/firestore";
import { db } from './firebase.js';
async function mark(conversationId, email) {
const messages = collection(db, 'messages');
const q = query(messages,
where('conversationId', '==' ,conversationId),
where('to', '==' , email),
where('seen', '==', false)
);
const querySnapshot = await getDocs(q);
querySnapshot.forEach((document) => {
const docId = document.id;
console.log(docId);
const ref = doc(db, `messages/${docId}`)
updateDoc(ref, { seen: true });
});
}
可能使用批處理也會提高查詢性能,如此線程所示。
看看官方文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.