我有一个带有一些type
字段的模型:
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)
当我在该模型上运行find
时,我需要能够按特定顺序排序,这意味着:
type = "Parrot"
的文档type = "Cat"
的文档type = "Dog"
的文档type = "Other"
的文档)我可以在JS代码本身上做到这一点,但想知道是否可以使用猫鼬find().sort()
Pet.find({}).sort(?)
任何帮助将不胜感激!
预先感谢
答案 0 :(得分:1)
您可以使用$addFields和$switch来准备一个字段,$sort可以在下一个聚合阶段使用:
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 }
}
])