我使用react和Firebase建立了一個訊息傳遞應用程式。當用戶創建一個新的群聊時,會創建一個新的檔案,其中有一個新的聊天ID(由Firebase隨機生成),并注明聊天的創建日期。群聊的參與者被添加到一個新的 "參與者 "集合中,該集合隨后被添加到新的聊天檔案中。以下是我的代碼:
db.collection('chats'/span>)。 add({ //add generated new chat document and id)
created: firebase.firestore.FieldValue。 serverTimestamp() // when new chat was created。
})
.then((docRef) => { /docRef.id包含新創建的聊天Id
console.log("docRef is" docRef.id) //這個作業,新的chatId被創建。
db.collection("chats"/span>)
.doc(docRef.id) //this isn't working, firebase is creating a new document with new random id, instead of use the docRef.id created above which represents the new chat.
.collection("participants")
.doc(auth.currentUser.id)
.set(currentUser)
.collection("chats")
.doc(docRef.id) //not working[/span
.collection("partants")
.doc(user.id)
.set(otherUser)
...
docRef.id起作用了,并且如console.log所示正確回傳。然而,當我試圖在下面的陳述句中參考它時,它卻不起作用,Firebase創建了一個全新的檔案,而不是添加到我想要的檔案中。
不知道我做錯了什么! 謝謝。
uj5u.com熱心網友回復:
對我來說,這段代碼看起來很好。你確定同一個函式沒有再運行,而這個函式正在創建新的聊天室嗎?此外,你沒有等待那些由set()回傳的承諾。試著將其重構為:
db.collection('chats').add({
created: firebase.firestore.FieldValue.serverTimestamp()
}).then(async (docRef) => {
// Async ^^
const newChatId = docRef.id
console.log("New chat ID:"/span> newChatId)
const newChatRef = db.collection("chats") 。 doc(docRef.id)
await newChatRef.collection("partants")。 doc(auth.currentUser.id)。set(currentUser)
await newChatRef.collection("associates")。 doc(user.id).set(otherUser)
})
另外,如果你一次添加多個檔案,可以嘗試使用Batch Writes,這樣,如果其中任何一個失敗,它們都會被添加或不添加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/332554.html
標籤:
