猫鼬-按特定顺序按字符串字段自定义排序

时间:2020-09-13 09:44:38

标签: node.js string mongodb sorting mongoose

我有一个带有一些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(?)

任何帮助将不胜感激!

预先感谢

1 个答案:

答案 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 }
    }
])

Mongo Playground