Node.js 如何按特定顺序对猫鼬进行排序?
我有猫鼬模型:Node.js 如何按特定顺序对猫鼬进行排序?,node.js,mongodb,mongoose,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)
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是这样做的,因此您可以将查询结果作为一个数组来获取,并使用自定义的比较函数,我通过添加类别的权重来解决这个问题。现在我的模型是这样的:
const schema = new Schema({
Name: { type: String },
Category: { type: String },
CategoryWeight: { type: Number },
Price: { type: Number }
})
const products = await Product.find().sort('-CategoryWeight')
我喜欢这样:
const schema = new Schema({
Name: { type: String },
Category: { type: String },
CategoryWeight: { type: Number },
Price: { type: Number }
})
const products = await Product.find().sort('-CategoryWeight')
我是说我该怎么做?这能回答你的问题吗?谢谢你的回复。我通过创造新的价值作为分类权重来解决这个问题。当我保存它时,我设置了重量