Tapas Mukherjee
Tapas Mukherjee

Reputation: 2178

Get Firestore collection and sub-collection document data together

I have the following Firestore database structure in my Ionic 5 app.

Book collection has documentes and each document has a Like sub-collection. The document names of Like collection are user IDs who liked the book.

I am trying to do a query to get the latest books and at the same time trying to get the document from Like sub-collection to check if I have liked it.

async getBook(coll) {
  snap = await this.afs.collection('Book').ref
    .orderBy('createdDate', "desc")
    .limit(10).get();

  snap.docs.map(x => {
    const data = x.data();
    coll.push({
      key: x.id,
      data: data.data(),
      like: this.getMyReaction(x.id)
    });
  }

async getMyReaction(key) {
    const res = await this.afs.doc('Book/myUserID').ref.get();
    if(res.exists) {
    return res.data();
  } else {
    return 'notFound';
  }
}

What I am doing here is calling the method getMyReaction() with each book ID and storing the promise in the like field. Later, I am reading the like value with async pipe in the HTML. This code is working perfectly but there is a little delay to get the like value as the promise is taking time to get resolved. Is there a solution to get sub-collection value at the same time I am getting the collection value?

Upvotes: 2

Views: 468

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317828

Is there a solution to get sub-collection value at the same time I am getting the collection value?

Not without restructuring your data. Firestore queries can only consider documents in a single collection. The only exception to that is collection group queries, which lets you consider documents among all collections with the exact same name. What you're doing right now to "join" these two collections is probably about as effective as you'll get.

The only way you can turn this into a single query is by having another collection with the data pre-merged from the other two collections. This is actually kind of common on nosql databases, and is referred to as denormalization. But it's entirely up to you to decide if that's right for your use case.

Upvotes: 2

Related Questions