ET-CS
ET-CS

Reputation: 7170

Mongoose - Custom sorting by a string field in specific order

I have a model with some type field:

const petOptions = Object.freeze({
  Dog: "Dog",
  Cat: "Cat",
  Parrot: "Parrot",
  Other: "Other",
});

const petSchema = new mongoose.Schema(
   {
      ...,
      type: {type: String, enum: petOptions, required: true},
   }
)

const Pet = mongoose.model("Pet", petSchema)

when I'm running find on that model, I need to be able to sort by specific order, meaning:

I can do that on the JS code itself but wonder if this is something that is possible to do using the mongoose find().sort()

Pet.find({}).sort(?)

Any help would be appreciated!

Thanks in advance

Upvotes: 1

Views: 1277

Answers (1)

mickl
mickl

Reputation: 49945

You can use $addFields and $switch to prepare a field you can $sort by in the next aggregation stage:

await Pet.aggregate([
    {
        $addFields: {
            sortField: {
                $switch: {
                    branches: [
                        { case: { $eq: [ "$type", "Parrot" ] }, then: 0 },
                        { case: { $eq: [ "$type", "Cat" ] }, then: 1 },
                        { case: { $eq: [ "$type", "Dog" ] }, then: 2 },
                    ],
                    default: 3
                }
            }
        }
    },
    {
        $sort: { sortField: 1 }
    }
])

Mongo Playground

Upvotes: 1

Related Questions