2017-10-15 111 views
2

我創建了一個名爲「books」的集合,其中我創建了一個名爲「users」的對象(又名.dict)。該對象如下所示:按對象查詢Firestore集合

users: { 
    5PPCTcdHOtdYjGFr7gbCEsiMaWG3: firebase.firestore.FieldValue.serverTimestamp() 
} 

現在我想查詢屬於某個用戶的所有書籍。我試過這個:

this.db 
    .collection('books') 
    .where(`users.${this.state.currentUser.uid}`, '>', 0) 
    .onSnapshot(querySnapshot => { 
     ... 

我從來沒有得到任何文件返回。我確定它應該匹配。

screenshot of Firestore console

要檢查我的理智,如果刪除where(...)部分,我得到的文件。只是我爲所有用戶獲取文檔。

我控制檯在.where()記錄該字符串,它看起來是正確的。

+0

作爲一個短期解決方案,我遍歷所有文檔並比較每個'doc.data()。users'。但這不是一個好的解決方案。 –

回答

1

我不能得到這個與.where()任何工作,但它似乎使用.orderBy()工作,免去:

.where(`users.${this.state.currentUser.uid}`, '>', 0) 

.orderBy(`users.${this.state.currentUser.uid}`) 
2

你查詢是錯誤的,因爲你是比較日期對象和數字,因此有兩個不同的東西。您可以通過運行以下兩行代碼來檢查它。

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 => { 
      ...