我有猫鼬模型:
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']
我怎么做?
答案 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')