如何按特定顺序对猫鼬进行排序?

时间:2020-08-30 12:59:10

标签: node.js mongodb mongoose

我有猫鼬模型:

const mongoose = require('mongoose')

const { Schema } = mongoose

const schema = new Schema({
    Name: { type: String }, 
    Category: { type: String },
    Price: { type: Number } 
})

module.exports = mongoose.model('Product', schema)

我必须按“类别”字段进行排序。排序顺序是

['Clothes', 'Accessories', 'Footwears']

我怎么做?

2 个答案:

答案 0 :(得分:1)

MongoDB服务器没有提供自定义排序功能的任何方式。

使用Javascript,因此您可以将查询的结果作为数组获取,并使用带有Array.sort的自定义比较功能

答案 1 :(得分:0)

我通过增加Category的权重解决了它。现在我的模型是这样的:

const schema = new Schema({
    Name: { type: String }, 
    Category: { type: String },
    CategoryWeight: { type: Number }, 
    Price: { type: Number } 
})

我这样排序:

const products = await Product.find().sort('-CategoryWeight')