如何按特定顺序对猫鼬进行分类



我有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']

我是怎么做的?

MongoDB服务器不提供任何方式来提供自定义排序功能。

Javascript确实如此,因此您可以将查询结果作为数组获取,并使用array.sort 的自定义比较函数

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

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

我这样排序:

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

最新更新