How to count association size with waterline/sails?

只谈情不闲聊 提交于 2019-12-07 13:33:20

问题


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.



来源:https://stackoverflow.com/questions/28168826/how-to-count-association-size-with-waterline-sails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!