过滤猫鼬对象数组

时间:2020-09-17 21:26:23

标签: mongodb typescript express mongoose

如何过滤对象数组的结果,而不是使用许多if

产品架构

let productSchema = new Schema({
name: {
    type: String,
    required: [true, "Name is requierd"]
},
description: {
    type: String
},
price: {
    type: String,
},
code: {
    type: String,
},
sku: {
    type: String,
},
images: [{
    filename: {
        type: String
    },
    publicUrl: {
        type: String
    },
    priority: {
        type: Number
    }
}],
subcategory: {
    type: Schema.Types.ObjectId,
    ref: 'Subcategory'
},
status: {
    type: String,
    default: 'A'
}
});

在产品查找和执行(子类别和类别)填充之前,获取所有具有可选过滤功能的产品

if (req.query.subcategory) {
    products = products.filter(product => product.subcategory.name === 
req.query.subcategory)
}
if (req.query.category) {
    products = products.filter(product => product.subcategory.category.name === req.query.category)
}
if(req.query.low && req.query.high){
    products = products.filter(product => Number(product.price) <= Number(req.query.high) && Number(product.price) >= Number(req.query.low))
}

0 个答案:

没有答案