2017-10-05 40 views
0

我想在firebase firestore中存儲一對多關係。假設我有一位作者,並且有屬於這位作者的書籍。我可以將其存儲在一個嵌套的關係:用firestore創建安全的類似REST的API

author/ 
    authorId1 : { 
    books: [{...}, {...}] 
    } 

但我也需要一種方法來列出所有的書籍,最好不通過每一個作者迭代(據我所知它被要求實時DB),所以我想我應該這樣做

author/ 
    authorId1 : { 
    books: [bookId1, bookId2] 
    } 
books/ 
    bookId1: {...} 
    bookId2: {...} 

但出於安全和性能的原因,我寧願不過濾前端。我發現這是可能的編寫查詢:

const bookRef = fireStore.collection('books'); 
debtorsRef.where('author', '==', authorId).then(...); 

這有望消除了性能問題,但它並不安全,因爲它會是可以從客戶端獲取其他作者的書籍。另外,我寧願將關係存儲在作者文檔中,而不是相反。

在例如Django Rest Framework的restful API上,我將查詢設置爲僅返回屬於給定用戶的書籍。 IIUC它可能與IAM,但基於這些例子,我不太清楚如何。

再說一遍,我想只有在作者的書籍屬性中列出了它的id時才能返回該書。理論上一本書可能屬於多個作者。

我想這是重複的,很多人都有這種擔憂,但我無法找到明確的答案來解決這個特定的用例。

回答

1

你可以寫Security Rules妥善保護您的查詢:

service cloud.firestore { 
    match /databases/{database}/documents { 
    match /books/{bookId} { 
     allow read: if request.resource.data.author == resource.data.author 
    } 
    } 
} 

注意,目前我們只支持對等式(==)(!=<<=等)的限制,而不是不平等

您可以擴展此概念,以維護每本書子集合中的所有者列表,並執行存在檢查(使用exists()函數):

service cloud.firestore { 
    match /databases/{database}/documents { 
    match /books/{bookId} { 
     allow read: if exists(/databases/$(database)/documents/books/$(bookId)/owners/$(request.auth.uid)) 
     match /owners/{ownerId} { 
     // Include other conditions that provide for ownership checks 
     allow write: if request.auth.uid == ownerId; 
     } 
    } 
    } 
} 
+0

所以如果我理解正確,目前沒有辦法檢查作者是否擁有bookId。你如何表達多對一的關係,每本書可以屬於多個用戶? – fodma1

+0

更新了包含此信息的答案 –