0

I have Mongoose model:

const mongoose = require('mongoose')

const { Schema } = mongoose

const schema = new Schema({
    Name: { type: String }, 
    Category: { type: String },
    Price: { type: Number } 
})

module.exports = mongoose.model('Product', schema)

And I have to sort by Category field. Sort order is

['Clothes', 'Accessories', 'Footwears']

How cat I do it?

Petr Vasilev
  • 150
  • 14

2 Answers2

1

The MongoDB server doesn't offer any way to provide a custom sort function.

Javascript does, so you can get the results from the query as an array, and use a custom compare function with Array.sort

Joe
  • 25,000
  • 3
  • 22
  • 44
1

I solved it by adding weight of Category. Now my model is like this:

const schema = new Schema({
    Name: { type: String }, 
    Category: { type: String },
    CategoryWeight: { type: Number }, 
    Price: { type: Number } 
})

And I sorting like this:

const products = await Product.find().sort('-CategoryWeight')
Petr Vasilev
  • 150
  • 14