是否有更简单的方法来查询 Cloud Firestore 以获取用户未看到的特定集合中的所有文档?
Is there an easier way to query Cloud Firestore to get all the documents in a specific collection that a user has NOT seen?
我正在 Angular 开发移动应用程序。该应用程序的主屏幕是一个竞赛页面,用户可以在其中选择他们更喜欢的两个项目中的哪一个。
初始化时,此页面会调用从 Cloud Firestore 检索比赛数据的后端代码。
我有一个已经可以使用的解决方案,它是:遍历在给定日期之后创建的所有比赛。但我担心这里的效率。我想要两样东西...
- 最小化用户正在下载的数据(减少延迟)
- 最大限度地减少查询和文档读取次数(降低成本)
returns 正是我要找的 TypeScript 示例:
import * as firebase from 'firebase/app';
contestsRef = firebase.firestore().collection('Contests');
async getAllContestsForUser() {
const rightNow = new Date(Date.now());
const contests = new Array<Contest>();
await this.contestsRef
.where('closeDateTime', '>', rightNow.toISOString())
.get()
.then(querySnapshot => {
querySnapshot.forEach(contest => {
this.contestsRef
.doc(contest.id)
.collection('Voters')
.doc(this.userId)
.get()
.then(voter => {
if (!voter.exists) {
// this user did not vote on contest
contests.push({ ...contest.data(), id: contest.id });
}
});
});
});
return contests;
}
这段代码的结果正是我想要的:一组用户以前没有见过的比赛,但我想知道是否有更好、更高效的方法使用 Firestore 查询来完成?
- Minimize the data that the user is downloading (reduce lag)
如果您想尽量减少获取的数据,您应该考虑减少在单个查询中获取的文档数量,因为在 Firestore 中,查询性能取决于您请求的项目数量,而不是您请求它们的项目数量。
- Minimize the number of queries and document reads (reduce cost)
最简单的解决方案是使用 limit()
调用。这将限制您从查询中获得的文档数量。这是一种常见的做法,因为一次获取所有数据并不是一个好的做法。所以我建议您以较小的块加载数据。
我正在 Angular 开发移动应用程序。该应用程序的主屏幕是一个竞赛页面,用户可以在其中选择他们更喜欢的两个项目中的哪一个。
初始化时,此页面会调用从 Cloud Firestore 检索比赛数据的后端代码。
我有一个已经可以使用的解决方案,它是:遍历在给定日期之后创建的所有比赛。但我担心这里的效率。我想要两样东西...
- 最小化用户正在下载的数据(减少延迟)
- 最大限度地减少查询和文档读取次数(降低成本)
returns 正是我要找的 TypeScript 示例:
import * as firebase from 'firebase/app';
contestsRef = firebase.firestore().collection('Contests');
async getAllContestsForUser() {
const rightNow = new Date(Date.now());
const contests = new Array<Contest>();
await this.contestsRef
.where('closeDateTime', '>', rightNow.toISOString())
.get()
.then(querySnapshot => {
querySnapshot.forEach(contest => {
this.contestsRef
.doc(contest.id)
.collection('Voters')
.doc(this.userId)
.get()
.then(voter => {
if (!voter.exists) {
// this user did not vote on contest
contests.push({ ...contest.data(), id: contest.id });
}
});
});
});
return contests;
}
这段代码的结果正是我想要的:一组用户以前没有见过的比赛,但我想知道是否有更好、更高效的方法使用 Firestore 查询来完成?
- Minimize the data that the user is downloading (reduce lag)
如果您想尽量减少获取的数据,您应该考虑减少在单个查询中获取的文档数量,因为在 Firestore 中,查询性能取决于您请求的项目数量,而不是您请求它们的项目数量。
- Minimize the number of queries and document reads (reduce cost)
最简单的解决方案是使用 limit()
调用。这将限制您从查询中获得的文档数量。这是一种常见的做法,因为一次获取所有数据并不是一个好的做法。所以我建议您以较小的块加载数据。