0

I have this model and I want to do a sort where the requests are sorted in this order(estadoPedido:Pendente,estadoPedido:Agendado,EstadoPedido:Concluido) Is that possible?

var requestSchema = new Schema({
  paciente: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: [true, "paciente is a required field"],
  },
  encaminhado: {
    type: Boolean,
    required: [true, "encaminhado is a required field"],
  }, //vem do body
  pessoaRisco: {
    type: Boolean,
    required: [true, "pessoaRisco is a required field"],
  }, //vem do body
  trabalhoRisco: {
    type: Boolean,
    required: [true, "trabalhoRisco is a required field"],
  }, //vem do body
  estadoPedido: {
    type: String,
    enum: ["Pendente", "Agendado", "Concluído", "Aguarda Resultado"],
  },
  resultado: { type: String, enum: ["Positivo", "Negativo"] },
  dataExame: {
    type: Date,
  },
  prioridade: { type: Number },
});
Fábio Pires
  • 89
  • 1
  • 2
  • 10

1 Answers1

0

Although there are solutions suggested here on Stack Overflow.

But the solutions as of now is to use aggregation pipeline, this approach can't be optimised with an index and requires a full collection scan to transform every document.

I would like to suggest an alternative workaround that might work well specifically for mongoose. But it does require data migration, but if you are still in early development, this is possible.

What you can do is modify your schema for estadoPedido:

estadoPedido: {
  type: String,
  enum: ["1_Pendente", "2_Agendado", "3_Concluído", "4_Aguarda", "5_Resultado"] // or use any other sortable prefix and separator symbol
  index: true,
  get(estadoPedido) {
    const [, value] = estadoPedido.split('_') // this assumes you don't originally have _ in your enum
    // or put your own logic to get your original value back
    return value
  }
}

Then when you want to query, you can just do

Request.find().sort({ estadoPedido: 1 })

mongoose will execute the get function and transform estadoPedido to original value on every document.

Warning

Keep in mind that this with this solution, you'll get the original value only in a mongoose document, when you use it somewhere else, e.g. in an aggregation, you will have to use the prefixed value

thammada.ts
  • 5,065
  • 2
  • 22
  • 33