【问题标题】:Firestore/Cloud functions: Finding a document in array of document references that match criteriaFirestore/Cloud 函数:在符合条件的文档引用数组中查找文档
【发布时间】:2020-03-14 18:59:56
【问题描述】:

使用 Firebase Cloud Functions 我想在文档引用数组中搜索包含某个其他文档的文档。我的结构如下所示;

Users 
   name
   email
   cars
      ref to cars/car1 for example
      ref to cars/car2 for example
Cars
   registration
   make
   model

有多个用户和多辆汽车。我需要搜索在他们的汽车阵列中有特定“汽车”的用户。

我正在尝试在云函数中编写它并具有以下内容;

admin.firestore()
              .collection('users')
              .where('cars', 'array-contains', registration)
              .get().then(doc => {
                console.log("TESTING: found the user " + doc.data().email)
                return
              }).catch(error => {
                console.error(error);
              });

我知道这目前只是在数组中搜索注册字符串。无论如何要搜索特定的文档参考。我正在使用 Node.js。


用于获取在数组中具有文档引用的所有文档的工作代码;

// Notify the owner of the car
            admin.firestore()
              .collection('users')
              .where('cars', 'array-contains', carRef)
              .get().then(snapshot => {
                snapshot.forEach(doc => {
                  console.log("TESTING found the user " + doc.data().email);
                  const message = {
                    notification: {
                      body: 'Your vehicle (' + carReg + ') recieved a report. Tap here to see!',
                    },
                    token: doc.data().cloudMessagingToken
                  };
                  sendMessage(message);
                });
                return
              }).catch(error => {
                console.error("Error finding a user that has the car in their garage");
                console.error(error);
              });

【问题讨论】:

    标签: firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    如果要使用引用类型字段进行查询,则需要向查询提供 DocumentReference 类型对象。如果您将 DocumentReference 传递给汽车,则查询应该可以工作。例如:

    const ref = admin.firestore().collection('Cars').doc(id)
    

    其中id 是文档的ID。

    但是,您不能使用引用文档中的字段值进行搜索。 Firestore 查询一次只能针对单个集合中的数据。使用您现在组织数据的方式,不可能对所有引用具有特定注册字符串字段的汽车的用户进行单个查询。对于该查询,您还需要为每个可以使用 array-contains 查询的用户存储一个注册字符串数组。

    是的,这涉及到数据的重复,它被称为“非规范化”。这在 nosql 类型的数据库中很常见,以启用您需要的查询。

    【讨论】:

    • 感谢您的回复,所以我已经存储了 ref,然后尝试通过它进行搜索。我仍然没有找到任何用户,并且肯定有用户在他们的阵列中使用那辆车。您认为您可以查看添加到问题中的代码,看看我是否在正确的跟踪中?
    • 没有看到所有的实际数据,真的不可能确定。
    • 认为我已经在您的帮助下解决了这个问题!将发布工作代码供其他人使用,以防他们发现它有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-07-25
    • 2019-01-09
    相关资源
    最近更新 更多