javascriptnode.jscountsails.jswaterline

Sails.js Count members of model / assiciation


I am trying to count members of a team in a table like this screenshot:

Screenshot sails.js count function

This is my "logic" but it wont work :(

  fn: async function () {

    var teams = await Team.find();
    var users = await User.find();

    var countMembers = await Team.count().where(users.team === teams.id);

    // Respond with view.
    return {teams, countMembers};

  }

The Table/ Model User is so, that 1 user can have 1 team. I Just want to count the members in the teams overview page.


Solution

  • Try this if you set up your modules i.e. with the attribute users: {collection: 'User', via: 'team'} for the collection of Teams, and User module with the attribute team: {model: 'Team'}.

    One-to-many docs: https://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-many#one-to-many

    fn: async function () {
    
        // Populate and count for many-to-one relationship (one team has many members)
        var teams = await Team.find().populate('users');
        teams = teams.map(team => ({
          ...team,
          countMembers: team.users.length,
        }));
    
        // Respond with a view.
        return { teams };
    
    }
    

    In your EJS view use:

    <% teams.forEach(team => { %>
     <%= team.countMembers %>
    <% }) %>
    
    

    Check here the options to take account of the limit of populated items to avoid mistakes in the counted value: https://sailsjs.com/documentation/reference/waterline-orm/queries/populate

    Alternatively, you could use native querys:

    https://sailsjs.com/documentation/reference/waterline-orm/datastores/send-native-query#-sendnativequery-

    Or even low level adapter usage:

    https://sailsjs.com/documentation/tutorials/using-mongo-db