【问题标题】:How do I limit records returned by FireBase firestore get() method?如何限制 FireBase firestore get() 方法返回的记录?
【发布时间】:2018-10-02 13:37:24
【问题描述】:

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

例如

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 : {
       }
    }

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

而在子集合消息中,key 就像 build from

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 毫秒,用户函数成功完成

我不知道我哪里错了。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

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

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 2010-11-05
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多