-
Ive tried various things between db rules, queries, etc... not sure what the right approach is. So i have a collection of groups. within each group i have a collection of members (which contains a uid). How do i get back all groups which a user is a member of? I didnt see a way to filter by a collection of child's prop. I can probably get it by separating groups and members, but its hard to tell what the right approach is. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Ok, so if I understand it correctly, this is your datamodel: {
"groups": {
"group1": {
"members": {
"member1": "user1uuid",
"member2": "user2uuid",
"member3": "user3uuid"
}
},
"group2": {
"members": {
"member1": "user3uuid"
}
}
}
} And you'd want to get all groups that, say user Option 1: Convert your members collections to arrays: {
"groups": {
"group1": {
"members": ["user1uuid", "user2uuid", "user3uuid"]
},
"group2": {
"members": ["user3uuid"]
}
}
} You can then create an array index (optional): Option 2 (more work): Convert the member strings to objects: {
"groups": {
"group1": {
"members": {
"member1": { "uuid": "user1uuid" },
"member2": { "uuid": "user2uuid" },
"member3": { "uuid": "user3uuid" }
}
},
"group2": {
"members": {
"member1": { "uuid": "user3uuid" }
}
}
}
} You can then create the index (required): // Get references to matching member nodes with a query:
const refs = await db.query('groups/$groupId/members').filter('uuid', '==', 'user3uuid').getRefs();
// Extract groupId's from the paths
const groupIds = refs.map(ref => ref.vars.groupId);
// Fetch only the matched groups:
const snapshot = db.ref('groups').get({ include: groupIds });
// snapshot.val() contains { "group1": { ... }, "group2": { ... } }
// Iterate groups:
snapshot.forEach(snap => {
console.log(`Found group ${snap.ref.key}: `, snap.val());
}) Note: no code above is tested, might contain typos... Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
awesome appreciate the quick response! thanks for both examples, option two is what i needed (each member object has a bunch of properties with it). |
Beta Was this translation helpful? Give feedback.
Ok, so if I understand it correctly, this is your datamodel:
And you'd want to get all groups that, say user
"user3uuid"
is a member of?Option 1:
Convert your members collections to arrays:
You can then create an array index (optional):