按对象查询Firestore集合
问题描述:
我创建了一个名为“books”的集合,其中我创建了一个名为“users”的对象(又名.dict)。该对象如下所示:按对象查询Firestore集合
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)
与
.orderBy(`users.${this.state.currentUser.uid}`)
答
你查询是错误的,因为你是比较日期对象和数字,因此有两个不同的东西。您可以通过运行以下两行代码来检查它。
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'。但这不是一个好的解决方案。 –