How to count association size with waterline/sails

2019-05-11 17:03发布

问题:

Using sails 0.10.5/waterline 0.10.15:

I cannot find an answer to a simple question: how to count the elements of an association without using populate() (which would load all data).

Let take a simple many2many relation with via:

User:
    attributes: {
        following: {
            collection: 'user',
            via: 'follower',
            dominant: true
        },

        follower: {
            collection: 'user',
            via: 'following'
        }

Now I need the size of the collections. Currently I try

User.findById(1).populateAll().exec(function(err, user) {
   // count of followings -> user.following.length;
   // count of followers-> user.follower.length;
}

which leads to loading the collections.

  • I'm missing a count function at collection level to avoid population/loading of data.
  • Is there a possibility to access the (auto generated) join tables to run a count-query directly on the join?

Something like:

User.findById(1).count({'followings'}).exec(function(err, followings) {
...}

or

UserFollowingFollow_FollowFollowing.countByUserFollowingFollowId(1).
    exec(function(err, followings) {
...}

回答1:

Waterline does offer the count query method and it can be used like this to solve your problem:

User.count().where({follower: followerId})
.exec(function(err, numberOfFollowings) {
  //numberOfFollowings will be the integer that you need
})

followerId is the id that you are passing to User.findOne() in your example.

You can also read the Waterline documentation about this.