Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by the association with populate

I have Articles and Comments linked by a one-to-many association (an Article can have many Comments).

I would like to obtain the most commented articles so I proceed like that :

function mostCommentedArticles () {
  var deferred = Q.defer();
  Article.find().populate('comments').sort('comments ASC').exec(deferred.makeNodeResolver());
  return deferred.promise;
}

BUT, I don't obtain the expected result : it doesn't sort at all (by Comments or anything else)

Is there an other way to proceed or is it an issue?

Thanks,

Pierre

like image 413
Pierre Avatar asked Dec 05 '22 06:12

Pierre


2 Answers

You pass it in the second parameter of .populate() like this:

.populate('foo', { sort: 'comments ASC' }).exec(...)
like image 115
Melvin Avatar answered Dec 23 '22 08:12

Melvin


Neither waterline (0.10.22) or sailsjs (v0.11) currently support this. You would need to process your return variable to reorder the data.

There is a ticket for this at https://github.com/balderdashy/waterline/issues/334

There is a difference between

 function mostCommentedArticles () {
  var deferred = Q.defer();
  Article.find().populate('comments').sort('comments.comment_date ASC').exec(deferred.makeNodeResolver());
  return deferred.promise;
 }

and

function mostCommentedArticles () {
  var deferred = Q.defer();
  Article.find().populate('comments', {sort: 'comment_date ASC'}).exec(deferred.makeNodeResolver());
  return deferred.promise;
 }

The first one should return all the articles and comments with everything sorted by the comment_date. The second one should return all your articles with the attached comments where the comments are sorted by date.

The second one should work using mongodb.

like image 42
richardw Avatar answered Dec 23 '22 08:12

richardw