简体   繁体   English

查询嵌套在 Firebase Firestore 中的 Object

[英]Query Nested Object in Firebase Firestore

I have in my Firestore database a list of documents that include this field 'Participants', as a nested object.我的 Firestore 数据库中有一个包含此字段“参与者”的文档列表,作为嵌套的 object。

数据库屏幕截图

I want to make a query that gets only one document from the database (to see if it exists or not) that has (for example) user id 5 and 6.我想进行一个查询,该查询仅从数据库中获取一个文档(以查看它是否存在),该文档具有(例如)用户 ID 5 和 6。

This is what my code looks like这就是我的代码的样子

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
  }

}

However, even if the chat with the participants object does indeed exist in the database, the result of the code indicates that it doesn't.然而,即使与参与者 object 的聊天确实存在于数据库中,代码的结果表明它不存在。

Here is the structure of the data when it is added to the database这是将数据添加到数据库时的数据结构

    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);

I appreciate any help on how to solve this problem.感谢有关如何解决此问题的任何帮助。 Thanks:)谢谢:)

on method collection, you can use empty property to see if the query getting data or not在方法集合上,您可以使用空属性来查看查询是否获取数据

if(chat.empty){
 alert('chat doesnt exist')
 //create chat
} else {
 alert('chat exists')
 //do something else
}

to get only one document from your query, you can use要从查询中只获取一个文档,您可以使用

chat.docs[0].data();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM