云 Firestore 深度获取与子集合



假设我们有一个名为"todos"的根集合。

此集合中的每个文档都具有:

  1. title : 字符串
  2. 名为 todo_items 的子集合

子集合中的每个文档todo_items都有

  1. title : 字符串
  2. completed:布尔值

我知道默认情况下在Cloud Firestore中查询是浅的,这很好,但是有没有办法查询todos并自动获得包含子集合todo_items的结果?

换句话说,如何使以下查询包含todo_items子集合?

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

这种类型的查询,尽管我们将来可能会考虑这样做。

如果有人仍然有兴趣知道如何在firestore中进行深度查询,这里有一个我想出的云函数getAllTodos版本,它返回所有具有"todo_items"子集合的"todos"。

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;
        })
}

我遇到了同样的问题,但是对于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

我使用了AngularFirestore(afs)和Typescript:

import { map, flatMap } from 'rxjs/operators';
import { combineLatest } from 'rxjs';
interface DocWithId {
  id: string;
}
convertSnapshots<T>(snaps) {
  return <T[]>snaps.map(snap => {
    return {
      id: snap.payload.doc.id,
      ...snap.payload.doc.data()
    };
  });
}
getDocumentsWithSubcollection<T extends DocWithId>(
    collection: string,
    subCollection: string
  ) {
    return this.afs
      .collection(collection)
      .snapshotChanges()
      .pipe(
        map(this.convertSnapshots),
        map((documents: T[]) =>
          documents.map(document => {
            return this.afs
             .collection(`${collection}/${document.id}/${subCollection}`)
              .snapshotChanges()
              .pipe(
                map(this.convertSnapshots),
                map(subdocuments =>
                  Object.assign(document, { [subCollection]: subdocuments })
                )
              );
          })
        ),
        flatMap(combined => combineLatest(combined))
      );
  }
  

正如其他答案中所指出的,您不能请求深度查询。

我的建议:尽可能少地复制数据

我在"养宠物"方面遇到了同样的问题。在我的搜索结果中,我需要显示用户拥有的每只宠物,但我也需要能够自己搜索宠物。我最终复制了数据。我将在每个用户上都有一个宠物数组属性以及一个宠物子集合。我认为这是我们在这类情况下能做的最好的事情。

根据文档,您需要对 firestore 进行 2 次调用.. 一个用于获取doc,另一个用于获取subcollection。要减少总时间,最好的办法是使用 promise.Allpromise.allSettled 并行进行这两个调用,而不是按顺序进行。

你可以尝试这样的事情:

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

最新更新