如何在Firestore中查询数组中的多个项目?("阵列含有")

Pas*_*cal 5 javascript firebase google-cloud-firestore

我正在使用Firestore和Javascript(vue.js)构建一对一的聊天应用程序.

我有一个对话和一个消息文档定义如下:

.collection( "coversation").DOC()

conversation: {
  participantsArray: ["id1", "id2"],
  participants: {
    id1: {
      /* details like avatar & name */
    },
    id2: {
      /* details like avatar & name */
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

.collection( "coversation").DOC( "foo" 的).收集( "消息").DOC()

message: {
  message: "foo"
}
Run Code Online (Sandbox Code Playgroud)

这很棒,所以我现在可以查询特定用户的所有会话,如下所示:

db.collection('conversations').where("participantsArray", "array-contains", userId)
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题如下:

我想查询特定的对话,如下所示:

db.collection('conversations')
  .where("participantsArray", "array-contains", userId)
  .where("participantsArray", "array-contains", chatpartnerId)
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为不允许双"array-contains"并抛出错误消息.

对我来说现在最有效的是打两个电话:

db.collection('conversations')
  .where(`participantsArray`, '==', [userId, chatpartnerId])

db.collection('conversations')
  .where(`participantsArray`, '==', [chatpartnerId, userId])
Run Code Online (Sandbox Code Playgroud)

然后检查这些查询是否返回对话.如果是这样,我会使用该对话添加消息,否则我会创建一个新对话.

它可以工作,但它是一堆代码并且非常低效.

所以我的问题是:

  1. 有一个更好的方法吗?
  2. 怎么做"array-contains"来检查多个项目?
  3. 我有一个participantArray和一个参与者字段,因为我没有弄清楚如何在一个对象数组上做"array-contains".有没有办法或者我应该保留两个领域?

PS: 之前,我曾经查询过参与者对象中的对象,如下所示:

db.collection("conversations").where(`participants.${userId}.id`, "==", userId)
Run Code Online (Sandbox Code Playgroud)

这是在"array-contains"存在之前查询的建议方法 - 但是当与orderBy结合时,我将不得不为每个用户创建一个索引,这实际上不是一个选项.

Pas*_*cal 4

我找到了一种方法来查询单个对话。

由于我 (1) 参与者的详细信息位于“ participants ”对象中,(2) 参与者 ID 位于“ partnersArray ”中,所以我可以按如下方式查询单个对话:

db.collection('conversations')
      .where(`participants.${userId}.id`, "==", userId)
      .where(`participants.${chatPartnerId}.id`, "==", chatPartnerId)
Run Code Online (Sandbox Code Playgroud)

所以我现在很高兴。然而,这三个问题仍然存在,所以如果有人能够正确回答它们,他们的答案将非常有价值:)