Cloud Firestore深获得子集合
问题描述:
假设我们有一个名为'todos'的根集合。Cloud Firestore深获得子集合
这个集合中的每个文件有:
-
title
:字符串 - 命名
todo_items
每一个文档中的子集合todo_items
子集合具有
-
title
:字符串 -
completed
:布尔
我知道,在云计算公司的FireStore查询浅默认情况下,这是伟大的,但有没有办法查询todos
和得到的结果,其中包括自动子集合todo_items
?
换句话说,我如何使下列查询包含todo_items
子集合?
db.collection('todos').onSnapshot((snapshot) => {
snapshot.docChanges.forEach((change) => {
// ...
});
});
答
这种类型的查询不受支持,虽然这是我们未来可能考虑的。
答
你可以尝试这样的
db.collection('coll').doc('doc').collection('subcoll').doc('subdoc')
希望这有助于东西!
+0
如果doc()键是动态生成的,该怎么办? – krv
答
我面临同样的问题,但与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
答
如果任何人仍然对知道如何在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;
})
}
请为此添加支持!这是一个非常重要的功能,实时数据库支持这个功能,所以我认为Firestore也应该如此 – user2476265
在你想出解决方案之前,你现在提出的建议是什么? –
如果有意义,请加上支持 –