Reputation: 9700
I have a collection called Entity
and each entity has a property called groups.
{
_id: xxx,
groups: [g1, g2, g3],
others...
}
An entity have at most a few groups. The groups don't change a lot and I don't store it in separate collections. A group array object look like this:
g1 = {
group_id: xxx,
name: xxx
}
Also I have a User
collection. Each user belongs to exactly 1 entity and 1 group. So basically we have a property called user.entity
and user.group
that references to exactly 1 entity document above.
When the user wants to get the entity information he can do GET /entity/123
. That's easy. What about entity groups? The possible choices are
GET /entity/123/group
or GET /group
.
Method 1 is straight forward. You're already telling people you want to get groups in entity 123
. So you can setup middlewares to turn 123
into req.entity
and return entity.groups
directly. But for admins he might want to query all groups in all entities and this API seems not right?
Reason why method 2 is also ok is because after I get req.user
I can check req.user.entity
, query entity 123
and return the groups. But I feel like I have to do extra condition checks to get the groups. Also if an admin wants to query all groups we will just have to query with a different condition and the query conditions could be messy/
So what is the better design here? Is there one that's more RESTful than the other? (by the way 1 user will have exactly 1 group and 1 entity and user.entity
will never change.)
Upvotes: 0
Views: 54
Reputation: 965
I'm working on a similar project and my solution is a mixture of both of your possible choices :
GET /group?entity_id=123
With this, I can directly access groups via entity_id
and can return all groups
when entity_id
is missing (ex. in case of admins).
This method depends whether your groups
are nested inside entities
, or they are independent (i.e can 2 different entities
have 2 different groups
with same id?).
If they are independent, you can also do something like :
GET /group/456
to access a group directly via it's id. However, this won't work if you've 2 groups with same ids. In that case, it's better to nest your url via entity/:id/group
Upvotes: 1