Limit Firestore function can be used to limit the number of documents retrieved (). I have users in a social web application who may have 3 to 10000 notifications. When a user authenticates, I retrieve 10 notifications for efficiency and then use an infinite scroll to retrieve more sequential fetches. Function appears as follows:
const db = admin.firestore();
let userData = {};
db
.collection('notifications')
.where('recipient', '==', req.user.handle)
.where('read', '==', 'false')
.orderBy('createdAt', 'desc')
.limit(10)
.get();
})
.then((data) => {
userData.notifications = [];
userData.lastKey = '';
data.forEach((doc) => {
userData.notifications.push({
recipient: doc.data().recipient,
sender: doc.data().sender,
createdAt: doc.data().createdAt,
screamId: doc.data().screamId,
type: doc.data().type,
read: doc.data().read,
notificationId: doc.id,
senderImg: doc.data().senderImg,
});
userData.lastKey = doc.id;
});
return res.json(userData);
})
.catch((err) => {
return res.status(500).json({ error: err.code });
});
I use the lastKey from the last fetched doc Id in combination with a fetchMoreNotifications function and firebase's startAfter() to fetch more notifications from the last one and so on.
I have a collection of notifications in my Firestore Database that include fields like: sender, createdAt, docId, sender, senderurl, and, most importantly, read:false; If a user has 14 unread notifications from comments, likes, and follows, I only show 10 from the first call and load the rest as the user scrolls down the notification tab. I'd rather set a minimum limit of results based on data values. For example, limit to at least 10 notifications even if 3 are unread, but if unread notifications are greater than 10, fetch all unread notifications but never the whole collection.
Something along the lines..
db
.collection('notifications')
.where('recipient', '==', req.user.handle)
.where('read', '==', 'false')
.orderBy('createdAt', 'desc')
// if less than 10 documents have the boolean read data field of false
// fetch 10 else fetch all the docs where read === false; => THE
// FOLLOWING limit() function will not work is only for explanation
// purposes.
.limit('read', '==', 'false' <= 10 ? 10 : 'read', '==', 'false')
.get();
Is it possible? I couldnt find anything on Firebase's docs.