【问题标题】:Mongoose-How to make custom sort?Mongoose-如何进行自定义排序?
【发布时间】:2020-05-16 00:58:16
【问题描述】:

我有这个模型,我想做一个排序,请求按这个顺序排序(estadoPedido:Pendente,estadoPedido:Agendado,EstadoPedido:Concluido) 这可能吗?

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 },
});

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    虽然 Stack Overflow 上有 solutions suggested here

    但目前的解决方案是使用aggregation pipeline,这种方法无法使用索引进行优化,并且需要完整的集合扫描来转换每个文档。

    我想建议一种替代解决方法,它可能特别适用于猫鼬。但它确实需要数据迁移,但如果您仍处于早期开发阶段,这是可能的。

    您可以做的是修改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
      }
    }
    

    那么当你想查询的时候,你可以这样做

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

    mongoose 将执行 get 函数并将 estadoPedido 转换为每个文档的原始值。

    警告

    请记住,使用此解决方案时,您只能在 mongoose 文档中获得原始值,当您在其他地方使用它时,例如在聚合中,您必须使用前缀值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-11
      • 2011-01-29
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2019-05-28
      • 2018-01-17
      • 2017-03-17
      相关资源
      最近更新 更多