简体   繁体   中英

How to Query a nested child from firebase angular?

// my db structure now

rcv : { 
visible: 'all', 
ids: [ 
[0] : userId, 
[1] : user2Id ]
 }

this is how i query to get the data it works.

//service.ts

getAlbumByUserId(userId) { 

    return this.afs.collection('albums', ref => ref.where('rcv.visible', '==', 'all').where('rcv.ids', 'array-contains', userId)).valueChanges();
     }

//component.ts

this.service.getAlbumByUserId(this.userId);

but i want to set the structure like this but i don't know how to query nested objects in firebase

// database structure

rcv : { 
visible: 'all',
 ids: {
 userId: {
id: userId
}
user2Id: {
id: user2Id
}
}
}

You're looking for the array-contains operator, which can check if a field that is an array contains a certain value.

You're already using the correct array-contains operator, but not with the correct syntax. The array-contains operator checks whether any element of your array is exactly the same as the value you pass in. So you need to pass in the complete value that exists in the array:

ref.where('rcv.visible', '==', 'all').where('rcv.ids', 'array-contains', { id: userId })

As you add more data to the array, it may become unfeasible to reproduce the entire array element for the query. In that case, the common approach is to add an additional field where you keep just the IDs.

So you'd end up with one field (say rcv.users ) where you keep all details about the receiving users, and one field (say rcv.ids ) where you just keep their IDs, and that you use for querying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM