[英]Query Nested Object in Firebase Firestore
我的 Firestore 數據庫中有一個包含此字段“參與者”的文檔列表,作為嵌套的 object。
我想進行一個查詢,該查詢僅從數據庫中獲取一個文檔(以查看它是否存在),該文檔具有(例如)用戶 ID 5 和 6。
這就是我的代碼的樣子
const chatsCollection = db.collection('chats');
async function createChat(myId, otherUserId){
chat = await chatsCollection
.where(`participants.${myId}`, "==", true)
.where(`participants.${otherUserId}`, "==", true)
.limit(1).get();
if(!chat.exists){
alert('chat doesnt exist')
//create chat
} else {
alert('chat exists')
//do something else
}
}
然而,即使與參與者 object 的聊天確實存在於數據庫中,代碼的結果表明它不存在。
這是將數據添加到數據庫時的數據結構
var chat_key = (Math.random() + 1).toString(36).substring(2);
chatData = {
key: chat_key,
created_at: new Date(),
participants: {
myId: true,
otherUserId: true,
}
}
chatsCollection.doc(chat_key).set(chatData);
感謝有關如何解決此問題的任何幫助。 謝謝:)
在方法集合上,您可以使用空屬性來查看查詢是否獲取數據
if(chat.empty){
alert('chat doesnt exist')
//create chat
} else {
alert('chat exists')
//do something else
}
要從查詢中只獲取一個文檔,您可以使用
chat.docs[0].data();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.