6

I would like to sort my Group-Model by the name of the departure_country with mongoose-paginate and NodeJS.

My Group-Schema:

  var GroupSchema = new Schema({
        name: String,
        flight_date: Date,
        ....
        departure_country: {type: Schema.ObjectId, ref: 'Country'},
        ....
  });

The Country-Schema:

 var CountrySchema = new Schema({
     name: String,
     code: String,
 });

Using the sortBy-option of mongoose-paginate sorts by the country's _ids and I don't know how to tell it to sort by the name.

molerat
  • 946
  • 4
  • 15
  • 43

1 Answers1

0

how about making the country code the _id of Country-Schema?

then departure_country: {type: String, ref: 'Country'}

That might actually be a better design. Country-Schemas _id would be small, and country codes shouldn't have collisions. Also in GroupSchema you'd use less space to store the "foreign key" departure_country.

then you'd be able to sort by departure_country and there's a chance the sort would also be valid for country name.

kio
  • 374
  • 1
  • 10
  • sometimes I need to display or even sort by the name of the country as well – molerat Oct 20 '15 at 11:02
  • @molerat don't think there's a way to do that since you're populating. you'd have to do that on the nodejs side. http://underscorejs.org has good functions for that. sortBy or even groupBy could be useful. – kio Oct 20 '15 at 17:00
  • If you get 50 of 10000 entries and sort those only, you will not have the same result as if sorting 10000 and then picking 50. – molerat Oct 20 '15 at 17:09
  • it's a consequence of data normalization in mongo. back to what I suggested, I think it can even work if you use the country name as an id. provided you have a pre-defined set of countries - so they're not user input (if they are user input, you need a way to normalize the name string to avoid duplicates). You could also make departure country an object and have both the id and the country name in there. – kio Oct 20 '15 at 17:46