Firestore query subcollections

2019-01-01 06:32发布

I thought I read that you can query subcollections with the new Firebase Firestore, but I don't see any examples. For example I have my Firestore setup in the following way:

  • Dances [collection]
    • danceName
    • Songs [collection]
      • songName

How would I be able to query "Find all dances where songName == 'X'"

8条回答
姐姐魅力值爆表
2楼-- · 2019-01-01 07:31

UPDATE Now Firestore supports array-contains

Having these documents

    {danceName: 'Danca name 1', songName: ['Title1','Title2']}
    {danceName: 'Danca name 2', songName: ['Title3']}

do it this way

collection("Dances")
    .where("songName", "array-contains", "Title1")
    .get()...

@Nelson.b.austin Since firestore does not have that yet, I suggest you to have a flat structure, meaning:

Dances = {
    danceName: 'Dance name 1',
    songName_Title1: true,
    songName_Title2: true,
    songName_Title3: false
}

Having it in that way, you can get it done:

var songTitle = 'Title1';
var dances = db.collection("Dances");
var query = dances.where("songName_"+songTitle, "==", true);

I hope this helps.

查看更多
一个人的天荒地老
3楼-- · 2019-01-01 07:31

It could be better to use a flat data structure.
The docs specify the pros and cons of different data structures on this page.

Specifically about the limitations of structures with sub-collections:

You can't easily delete subcollections, or perform compound queries across subcollections.

Contrasted with the purported advantages of a flat data structure:

Root-level collections offer the most flexibility and scalability, along with powerful querying within each collection.

查看更多
登录 后发表回答