2017-10-06 117 views
20

假設我們有一個名爲'todos'的根集合。Cloud Firestore深獲得子集合

這個集合中的每個文件有:

  1. title:字符串
  2. 命名todo_items

每一個文檔中的子集合todo_items子集合具有

  1. title:字符串
  2. completed:布爾

我知道,在雲計算公司的FireStore查詢淺默認情況下,這是偉大的,但有沒有辦法查詢todos和得到的結果,其中包括自動子集合todo_items

換句話說,我如何使下列查詢包含todo_items子集合?

db.collection('todos').onSnapshot((snapshot) => { 
    snapshot.docChanges.forEach((change) => { 
    // ... 
    }); 
}); 

回答

17

這種類型的查詢不受支持,雖然這是我們未來可能考慮的。

+14

請爲此添加支持!這是一個非常重要的功能,實時數據庫支持這個功能,所以我認爲Firestore也應該如此 – user2476265

+0

在你想出解決方案之前,你現在提出的建議是什麼? –

+0

如果有意義,請加上支持 –

0

你可以嘗試這樣的

db.collection('coll').doc('doc').collection('subcoll').doc('subdoc') 

希望這有助於東西!

+0

如果doc()鍵是動態生成的,該怎麼辦? – krv

0

我面臨同樣的問題,但與IOS,任何方式,如果我得到您的問題,如果您使用自動ID的待辦事項集合文件,它將很容易,如果您將文件ID作爲字段存儲與標題字段 在我的情況:

let ref = self.db.collection("collectionName").document() 

let data = ["docID": ref.documentID,"title" :"some title"] 

所以,當您檢索可以說的待辦事項的數組,當點擊任何項目可以導航的路徑

ref = db.collection("docID/\(todo_items)") 

我希望我可以給這麼容易你確切的代碼,但我不熟悉Javascript

0

如果任何人仍然對知道如何在firestore中進行深層查詢感興趣,下面是我已經提出的一個雲函數getAllTodos的版本,它返回所有'todos',其中包含'todo_items'子集合。

exports.getAllTodos = function (req, res) { 
    getTodos(). 
     then((todos) => { 
      console.log("All Todos " + todos) // All Todos with its todo_items sub collection. 
      return res.json(todos); 
     }) 
     .catch((err) => { 
      console.log('Error getting documents', err); 
      return res.status(500).json({ message: "Error getting the all Todos" + err }); 
     }); 
} 

function getTodos(){ 
    var todosRef = db.collection('todos'); 

    return todosRef.get() 
     .then((snapshot) => { 
      let todos = []; 
      return Promise.all(
       snapshot.docs.map(doc => { 
         let todo = {};     
         todo.id = doc.id; 
         todo.todo = doc.data(); // will have 'todo.title' 
         var todoItemsPromise = getTodoItemsById(todo.id); 
         return todoItemsPromise.then((todoItems) => {      
           todo.todo_items = todoItems; 
           todos.push(todo);   
           return todos;     
          }) 
       }) 
      ) 
      .then(todos => { 
       return todos.length > 0 ? todos[todos.length - 1] : []; 
      }) 

     }) 
} 


function getTodoItemsById(id){ 
    var todoItemsRef = db.collection('todos').doc(id).collection('todo_items'); 
    let todo_items = []; 
    return todoItemsRef.get() 
     .then(snapshot => { 
      snapshot.forEach(item => { 
       let todo_item = {}; 
       todo_item.id = item.id; 
       todo_item.todo_item = item.data(); // will have 'todo_item.title' and 'todo_item.completed'    
       todo_items.push(todo_item); 
      }) 
      return todo_items; 
     }) 
} 
相關問題