簡體   English   中英

如何限制FireBase firestore get()方法返回的記錄?

[英]How do I limit records returned by FireBase firestore get() method?

根據問題,我想按時間基礎檢索記錄。

例如

 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM