Firebase 按对象查询Firestore集合
我创建了一个名为“books”的集合,在其中我创建了一个名为“users”的对象(aka.dict)。该对象如下所示:Firebase 按对象查询Firestore集合,firebase,google-cloud-firestore,Firebase,Google Cloud Firestore,我创建了一个名为“books”的集合,在其中我创建了一个名为“users”的对象(aka.dict)。该对象如下所示: users: { 5PPCTcdHOtdYjGFr7gbCEsiMaWG3: firebase.firestore.FieldValue.serverTimestamp() } 现在我想查询属于某个用户的所有书籍。我试过这个: this.db .collection('books') .where(`users.${this.state.currentUser
users: {
5PPCTcdHOtdYjGFr7gbCEsiMaWG3: firebase.firestore.FieldValue.serverTimestamp()
}
现在我想查询属于某个用户的所有书籍。我试过这个:
this.db
.collection('books')
.where(`users.${this.state.currentUser.uid}`, '>', 0)
.onSnapshot(querySnapshot => {
...
我从来没有收到任何退回的文件。我相信这是一个应该匹配的东西
为了检查我的理智,如果我删除where(…)
部分,我会得到文档。我只需要为所有用户获取文档
我将该字符串记录在
.where()
中,它看起来是正确的 我也无法使用.where()
实现此功能,但使用.orderBy()
似乎可以实现此功能,替换为:
.where(`users.${this.state.currentUser.uid}`, '>', 0)
与
您的查询是错误的,因为您将日期对象与数字进行比较,因此是两件不同的事情。您可以通过运行下面的两行代码来检查它
console.log(typeof(firebase.firestore.FieldValue.serverTimestamp()))
console.log(typeof(0))
所以你有两个选择:
1-您可以将日期对象与数据对象进行比较,如下所示
this.db
.collection('books')
.where(`users.${this.state.currentUser.uid}`, '>', new Date(0))
.onSnapshot(querySnapshot => {
...
2-或者您可以以毫秒为单位保存日期,并将其与数字进行比较
users: {
5PPCTcdHOtdYjGFr7gbCEsiMaWG3: new Date().getTime();
}
this.db
.collection('books')
.where(`users.${this.state.currentUser.uid}`, '>', 0)
.onSnapshot(querySnapshot => {
...
作为一个短期解决方案,我循环所有文档并比较每个
doc.data().users
。但这不是一个好的解决方案。是的,orderBy本身似乎就足够了,但谁知道它可能会使用新的日期(0)进行更改更安全
users: {
5PPCTcdHOtdYjGFr7gbCEsiMaWG3: new Date().getTime();
}
this.db
.collection('books')
.where(`users.${this.state.currentUser.uid}`, '>', 0)
.onSnapshot(querySnapshot => {
...