pdorns
pdorns

Reputation: 275

How to structure database models in sails for a many-to-many association

I'm creating a web app that consists of teams and users. Users can belong to more than one team, and teams consist of many users. To implement this on the backend, I've followed Waterline guides like this one to create the association table, and have created waterline models for a User and a Team. Having done this, I'm still not sure how my api could return, for example, a list of users that belong to a certain team. I'm not sure what the best practice here is. Should I create an array within the team model that simply stores the names of the team's users, and return that when needed? Or is there an efficient way to query the association table to get the specific team's list of users? Any help would be greatly appreciated!

Upvotes: 1

Views: 88

Answers (2)

Alexis N-o
Alexis N-o

Reputation: 3993

Using blueprints for your api, you will automatically retrieve the team's users.

If you want to use a custom controller, you can obtain the same result using populate().

Team.findOne({id:id}).populate('users').exec(function(err, team){
  console.log(team.toJSON())
});

Upvotes: 2

user2319883
user2319883

Reputation: 27

My suggestion is that rethink your business logic, if you are using a database like mongo plan your models like objects, y guess your main item there is the user like:

var UserModel = {
  name: String,
  age: Number,
  teams:[
    {
      name: String,
      memberSince: Date
    },
    {
      name: String,
      memberSince: Date
    }
  ]
};

then to retrieve the list of users of some team the query looks like

var memberList = UserModel.find({teams.name:<your team>});

Dont use any ids to bind collections just use an array to use them in your user collection.

Upvotes: 1

Related Questions