我有这个模型,我想做一个排序,其中请求按此顺序排序(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 },
});
答案 0 :(得分:0)
尽管堆栈溢出中有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 })
猫鼬将执行get函数,并将estadoPedido
转换为每个文档的原始值。
警告
请记住,通过此解决方案,当您在其他地方使用它时,只有在猫鼬文档中才能获得原始值,例如在聚合中,您将必须使用前缀值