Home > other >  How to get access from one collection to another collection in firebase
How to get access from one collection to another collection in firebase

Time:09-17

enter image description here

how to get access from one collection to another collection in firebase in JS v9

CodePudding user response:

Firebase's JS API v9 brought different changes. One of the biggest changes is the fact that the DocumentReference don't allow the access to subcollections anymore. Or at least, not directly from the DocumentReference itself, how we used to to with v8.

In v8, for example, we could do something like this:

//say we have a document reference
const myDocument = db.collection("posts").doc(MY_DOC_ID);

//we can access the subcollection from the document reference and, 
//for example, do something with all the documents in the subcollection
myDocument.collection("comments").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        // DO SOMETHING
    });
});

With v9, we have a different approach. Let's say we get our document:

const myDocument = doc(db, "posts", MY_DOC_ID);

As you can note, the way we write the code is different. In v8 we used to write it in a procedural way. With v9, everything switched to a more functional way, where we can use functions such as doc(), collection() and so on. So, in order to do the same thing we did with the above example and do something with every doc in the subcollection, the code for v9 API should look like this:

const subcollectionSnapshot = await getDocs(collection(db, "posts", MY_DOC_ID, "comments"));
subcollectionSnapshot.forEach((doc) => {
  // DO SOMETHING
});

Note that we can pass additional parameters to functions such as collection() and doc(). The first one will always be the reference to the database, the second one will be the root collection and from there onward, every other parameter will be added to the path. In my example, where I wrote

collection(db, "posts", MY_DOC_ID, "comments")

it means

  • go in the "posts" collection
  • pick the document with id equals to MY_DOC_ID
  • go in the "comments" subcollection of that document
  • Related