简体   繁体   中英

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.

数据库屏幕截图

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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