I have products model like this
const productSchema = new mongoose.Schema({
categories:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}
})
and category model
const productSchema = new mongoose.Schema({
title: { type: String, required: true }
})
now
I wanna Filter Products by array of categories id
I send array of categories id [_1234464 , _987654321]
in request body
controller/products
exports.get = async (req, res, next) => {
categories=req.body.categories // is like [_1234464 , _987654321] ;
const filteredProducts= productModel.find({ /* i dont know what to write here*/ })
})
CodePudding user response:
exports.get = async (req, res, next) => {
categories=req.body.categories // is like [_1234464 , 987654321] ;
const filteredProducts= productModel.find({ categories:{$in:categories} })
})
CodePudding user response:
Here is the answer where it filters for categories only if they are set:
exports.get = async (req, res, next) => {
categories=req.body.categories // is like [_1234464 , 987654321] ;
const filteredProducts= productModel.find(categories? { categories:{$in:categories}: {} })
})