Mongoose Query - Sort by Name field type

10,110 views
Skip to first unread message

James Lukensow

unread,
Mar 13, 2015, 2:58:14 AM3/13/15
to keyst...@googlegroups.com
Is it possible to sort a query by the Name Type field?

The field is named: name

I tried the following:

.sort('name')

.sort('name.first')

Anyone have any ideas?

Vito Belgiorno-Zegna

unread,
Mar 25, 2015, 11:42:39 PM3/25/15
to keyst...@googlegroups.com
Hey James,

The Mongoose API docs cover queries, including .sort here: 


This is the kind of syntax you want to follow:

model.find().sort({ name: 'criteria' }).exec(function(err, model) { ... });


'criteria'
can be:
asc, desc, ascending, descending, 1, or -1


Hope that helps.

Jed Watson

unread,
Mar 26, 2015, 5:28:48 PM3/26/15
to keyst...@googlegroups.com
Hey Vito and James,

The shorthand syntax should work too, as a simplification you can .sort('path') and .sort('-path') for desc

With the name field there is absolutely no reason it wouldn't sort like any other field in MongoDB.

Although you would need to sort by the full path 'name.first' or 'name.last' - sorting on just 'name' will have no effect.

Without seeing your schema unfortunately it's hard to help more specifically, I recommend experimenting with the mongo shell or RoboMongo to visualise your queries if you're having trouble figuring out what's going on.

Hope that helps!

- Jed.

James Lukensow

unread,
Apr 6, 2015, 5:52:57 PM4/6/15
to keyst...@googlegroups.com
Oh jeeze, I can't believe I didn't try q.sort('name.last'). Thanks all!

Ryan Cole

unread,
Apr 7, 2015, 2:22:33 PM4/7/15
to keyst...@googlegroups.com
Hey James there's a mongo course running now by mongo university. Covers all this stuff. :) I'm in it now too!
Reply all
Reply to author
Forward
0 new messages