【问题标题】:How to get the document ref to a where clause firestore?如何将文档引用获取到 where 子句 firestore?
【发布时间】:2020-07-21 04:59:25
【问题描述】:

如何获得对where 子句结果的引用?我的数据库结构如下:

- Restaurants
     - Restaurant 1
         - Ratings (sub collection)
         - Statistics

所以我有一个餐厅集合,其中每个文档都是特定的餐厅。在每个文档中,都有一个名为 rating 的子集合。 我正在尝试获取对餐厅 1 的文档引用,以便向其添加一些一般统计信息,以及对子集合的引用,以便添加评分。我目前无法获得对餐厅 1 的引用,因为我使用了 where 子句,它不返回引用。

var restaurantRef = firestore.collection("restaurants").where("name", "==", "Neubig Hall")

  function addFeedback(data) {
    return firestore.runTransaction((transaction) => {
      var feedbackRef = restaurantRef.get().then(snapshot => {snapshot.forEach(doc => doc.ref.collection("feedback"))});

这是说restaurantRef 不是文档引用。我在 React Native 应用程序中使用它。

【问题讨论】:

  • 请编辑问题以显示未按您期望的方式工作的代码。请清楚您在编写该代码时遇到的困难。
  • 您正在使用哪种语言进行编程?每种语言都不同。
  • 刚刚添加了我的代码,我正在使用 java-script 进行本机反应

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

从 API 文档中可以看出,where() 返回一个 Query 对象。这不是 DocumentReference。

即使您认为查询只会返回一个文档,您仍然必须编写代码来处理它可能在QuerySnapshot 对象中返回零个或多个文档的事实。我建议查看documentation on queries 以查看示例。

另请注意,您不能在事务中使用 Query 对象。交易需要一个 DocumentReference,而这里又没有。

如果您确实想执行查询并使用它返回的文档,它会更像这样:

const restaurantQuery = firestore.collection("restaurants").where("name", "==", "Neubig Hall")
restaurantQuery.get().then(querySnapshot => {
    if (!querySnapshot.empty) {
        const snapshot = querySnapshot.docs[0]  // use only the first document, but there could be more
        const documentRef = snapshot.ref  // now you have a DocumentReference
        //  ... use your DocumentReference ...
    }
    else {
        // decide what you want to do if the query returns no documents.
    }
})

【讨论】:

    【解决方案2】:

    您的代码中有一个错字:您调用restauranteRef.get(),在restaurant 的末尾加上e,而您的查询声明为restaurantRef,没有e

    你应该这样做:

      function addFeedback(data) {
        return firestore.runTransaction((transaction) => {
          var feedbackRef = restaurantRef.get()then(...)   // <- without e
          // ...
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-21
      • 2022-01-20
      • 2020-11-28
      • 2021-01-07
      • 2019-06-08
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多