Firestore查询多个字段中相同值的内容。

4

在云Firestore中,是否可以查询文档中多个字段中包含相同值的数据?

例如:

await firestore()
      .collection('chats')
      .where('ownerUserId', '==', user.uid)
      .where('chatUserId', '==', user.uid)
      .orderBy('createdAt', 'desc')
      .get()

更准确地说,应该是这样的

await firestore()
      .collection('chats')
      .where('ownerUserId', '==', user.uid || 'chatUserId', '==', user.uid)
      // .where('chatUserId', '==', user.uid)
      .orderBy('createdAt', 'desc')
      .get()
1个回答

2

对于“OR”条件,我们需要执行多个查询,如下所示:

//We define an async function that takes user uid and return chats
async function getChatsByUserOrOwner(userId) {
      const chatsRef=firestore().collection('chats')
      const ownerChats = chatsRef.where('ownerUserId', '==', userId).orderBy('createdAt', 'desc').get();
      const userChats = chatsRef.where('chatUserId', '==', userId).orderBy('createdAt', 'desc').get();  
      const [ownerChatsSnapshot, userChatsSnapshot] = await Promise.all([
              ownerChats,
              userChats
            ]);
      const ownerChatsList = ownerChatsSnapshot.docs;
      const userChatsList = userChatsSnapshot.docs;
      const allChats = ownerChatsList.concat(userChatsList);
      return allChats;
  }

现在我们将调用此函数以获取所需结果:
//We call the asychronous function
getChatsByUserOrOwner(user.uid).then(result => {
    result.forEach(docSnapshot => {
        console.log(docSnapshot.data());
    });
});

当我对同一引用进行多个请求时,我遇到了以下错误,有什么想法吗: FirebaseError:缺少或权限不足。 - Zukzuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接