Sorting populate

5,265 views
Skip to first unread message

Samuel Morello

unread,
Dec 2, 2011, 10:54:10 AM12/2/11
to mongoo...@googlegroups.com
Hi, 

Is it possible to sort populated docs ? 

I would like to do something like this but can not find how ? 

MyModel
  .find({})
  .populate('test', ['field1'], null, {sort: {label: 1}})
  .run ... 

Thanks, 
Samuel 

Aaron Heckmann

unread,
Dec 2, 2011, 12:30:02 PM12/2/11
to mongoo...@googlegroups.com
as of 2.4.1 yes.

Model.find().populate(path, fields, conditions, options);

so for options you could use 
 
{ sort: 'order' } // ascending
{ sort: [['order', 1 ]] } // ascending
{ sort: [['order', 'asc' ]] } // ascending
{ sort: [['order', 'desc' ]] } // ascending
{ sort: [['order', -1 ]] } // descending
{ sort: [['order', 'desc' ]] } // descending
{ sort: [['order', 'descending' ]] } // descending

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoo...@googlegroups.com
To unsubscribe from this group, send email to
mongoose-orm...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en



--
Aaron


Samuel Morello

unread,
Dec 2, 2011, 12:34:39 PM12/2/11
to mongoo...@googlegroups.com
excellent 
Thanks, 
Samuel 

Aaron Heckmann

unread,
Jul 26, 2012, 8:56:03 PM7/26/12
to mongoo...@googlegroups.com
Here is a breakdown of what is happening (you can see this for yourself by enabling debug mode `mongoose.set('debug', true)`):

1) File.find is run.
2) After it calls back and no error occurred, a separate populate query is executed for each item in the result set, passing the appropriate arguments such as 'sort' in this case. If `owner_ref` is a single objectid, sorting will have no affect because, well, there will be at most one document to sort. If its an array of objectids, the sort argument will sort just that one array of results.

Mongo has no joins. The only way to sort populated documents is todo it manually after you receive all results.

On Jul 26, 2012, at 1:35 PM, august black <augus...@gmail.com> wrote:

Hi, I am trying to sort on top of populate as is described in this thread, but it simply does not work for me.

I have a File schema with a ref to a User schema called "owner_ref".
The User schema has:  { _id: ObjectId, profile: { name : { display: String } } }   // embedded

I do:

var q = File.find( {} );
q.populate('owner_ref', ['_id', 'profile'], null,  { sort : [["profile.name.display", parseInt( sp.direction) ]] }  );


Is there something wrong with my query?   Are you not allowed to sort on dot notation?

thanks! -august.


--
Reply all
Reply to author
Forward
0 new messages