简体   繁体   中英

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

As per the question, I want to retrieve records as per Time basis.

eg

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

User is collection inside that name is document, and messages is subcollection.

And in subcollection messages key is like build from

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

I want to retrieve all messages which are posted today and yesterday.

My Unsuccessful Try :

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);
                    });

OUTPUT
User function triggered, starting execution Execution took 3987 ms, user function completed successfully

I don't know where I'm going wrong.

You're trying to get a subcollection from a query, which isn't possible. You can only get a subcollection from a specific document. This means you first need to execute the query to find the document(s) matching your condition.

Since it seems your document's are named after the same UID that you're querying on, you might also be able to get away without a query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM