javascript - 如何限制 FireBase firestore get() 方法返回的记录?

标签 javascript firebase google-cloud-firestore

根据问题,我想根据时间检索记录。

例如

users:(collection) {
      uid(document) : {
          uid(field) : 'someuid',
          name(field) : 'somename',
          messages(subcollection) : {
            '1538484652672'(document) :  {
                 text(field) : 'somemessages',
                 time(field) : 1538484652672,
            }
            '1538483652672'(document) :  {
                 text(field) : 'somemessages',
                 time(field) : 1538483652672,
            }
            '1538483652672'(document) :  {
                 text(field) : 'somemessages',
                 time(field) : 1538483652672,
            }
            .
            .
            .
            .
            .
            (possible many thousands entries)
          }
       },
       uid : {
       }
    }

用户是集合,名称是文档,消息是子集合。

在子集合消息中,键就像构建自

console.log(new Date().getTime());

我想检索今天和昨天发布的所有消息。

我不成功的尝试:

let backYesterday = new Date(today.getFullYear(), today.getMonth() , today.getDate()-1).getTime();
db.collection('users').where("uid","==",uid).collection('messages')
                     .where("time" , '>' , backYesterday).get()
                     .then(function(querySnapshot) {
                        console.log(querySnapshot);
                        querySnapshot.forEach(function(doc) {
                            console.log(doc.id, " => ", doc.data());
                        });
                    })
                    .catch(function(error) {
                        console.log("Error getting documents: ", error);
                    });

输出
用户函数触发,开始执行 执行耗时 3987 毫秒,用户函数成功完成

我不知道我错在哪里。

最佳答案

您正在尝试从查询中获取子集合,但这是不可能的。您只能从特定文档获取子集合。这意味着您首先需要执行查询来查找与您的条件匹配的文档。

由于您的文档似乎是以您正在查询的相同 UID 命名的,因此您也许无需查询即可逃脱:

var userDoc = db.collection('users').doc(uid)
userDoc.collection('messages')
       .where("time" , '>' , backYesterday).get()

关于javascript - 如何限制 FireBase firestore get() 方法返回的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52609545/

相关文章:

javascript - Api PUT 请求显示为 "cancelled",错误消息为 "TypeError: failed to fetch"

javascript - 有人做过长文档平滑滚动条/导航栏吗?

android - 如何只显示一次 Firebase 数据?

android - 如何在 Firestore 中使用 'where'

android - Firestore 安全规则 : PERMISSION DENIED when Batching

javascript - 裁剪后调整图像大小

javascript - 如何使用 jQuery 将 ISO 8601 格式的日期转换为时间戳?

android - 数据库异常 : Class is missing a constructor with no arguments

android - 将 Google 项目迁移到 Firebase 控制台

python - Google Cloud Firestore 触发器未检测到对数据库的写入