Cloud Firestore deep get with subcollection

24,353

Solution 1

This type of query isn't supported, although it is something we may consider in the future.

Solution 2

If anyone is still interested in knowing how to do deep query in firestore, here's a version of cloud function getAllTodos that I've come up with, that returns all the 'todos' which has 'todo_items' subcollection.

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;
        })
}
Share:
24,353
mechanical-turk
Author by

mechanical-turk

Updated on July 05, 2022

Comments

  • mechanical-turk
    mechanical-turk almost 2 years

    Let's say we have a root collection named 'todos'.

    Every document in this collection has:

    1. title: String
    2. subcollection named todo_items

    Every document in the subcollection todo_items has

    1. title: String
    2. completed: Boolean

    I know that querying in Cloud Firestore is shallow by default, which is great, but is there a way to query the todos and get results that include the subcollection todo_items automatically?

    In other words, how do I make the following query include the todo_items subcollection?

    db.collection('todos').onSnapshot((snapshot) => {
      snapshot.docChanges.forEach((change) => {
        // ...
      });
    });
    
  • ProfessorManhattan
    ProfessorManhattan over 6 years
    Please add support for this! This is a very important feature and the Real-time database supports this so I think Firestore should too
  • Van Du Tran
    Van Du Tran over 6 years
    What do you suggest we do now, before you come up with a solution?
  • Joshua Kemmerer
    Joshua Kemmerer over 6 years
    Please add support for this if it makes sense
  • snort
    snort over 6 years
    Maybe I’m crazy but I fully expected this to work out of the box as a basic feature given the reference type. Otherwise, how is that type any more useful than a string? This is precisely the kind of problem that I asumed Firestore was built to solve. Please implement this!
  • krv
    krv over 6 years
    what if the doc() keys are dynamically generated?
  • Arco
    Arco about 6 years
    Will deep querying be anounced on the next Google I/O? Shall I wait till May 8 or is it smarter to go on with the bulky solution of making arrays on docs instead of querying... Hours of waiting (to no purpose?) or (maybe) hours of reprogramming: Difficult decision!
  • Anggrayudi H
    Anggrayudi H about 6 years
    Today is May 27th, 2018. Is this feature available now? Was this already on Firebase's roadmap?
  • Nikolai Hegelstad
    Nikolai Hegelstad about 6 years
    @danmcgrath Do you have an answer with regards to the roadmap?
  • kiwicopple
    kiwicopple over 5 years
    Not sure why this isn't pointed out in the docs - a bit frustrating that developers have to find this out through StackOverflow, probably because they have reached this limitation after days of coding. This is really baseline functionality, so I'm suprised that the response from Google is "may consider it for the future", without a) workarounds or b) reasons why it's only a consideration and not on the product roadmap
  • Jonio
    Jonio almost 5 years
    If I try to print result todos, my subcollection are in this format: [Object][Object]...
  • Nimish David Mathew
    Nimish David Mathew over 4 years
    What about inconsistencies in the duplicated data?
  • blueberry_chopsticks
    blueberry_chopsticks over 4 years
    Use Firebase Cloud Functions on relevant changes to update the duplicated data.
  • 6by3
    6by3 over 4 years
    Can the use of Map type replace some places where a subcollection is used
  • benjiman
    benjiman over 4 years
    Also not sure why this feature isn't available... however, don't forget you get billed per read and I guess a populated query would count as one request only ;-)
  • DMonkey
    DMonkey over 4 years
    Has this << still >> not been added as a feature? I came across this problem using flutter + firestore and am rather perplexed.
  • Hamed Hamedi
    Hamed Hamedi over 3 years
    It's really funny, they came across the demand three years ago !!! I think the people left it for good, till now that we thought of a great combination with flutter. But ...
  • Dan McGrath
    Dan McGrath over 3 years
    We still see the desire for this feature, it just hasn't got near the top of the list based on all the input into the roadmap we have.
  • Ryan Loggerythm
    Ryan Loggerythm almost 3 years
    why is this so downvoted? this is literally the correct answer as stated in the official documentation! firebase.google.com/docs/firestore/data-model
  • Sajad Abdollahi
    Sajad Abdollahi over 2 years
    2021/09 and we still looking for this feature