skip to Main Content

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*/  })
})

2

Answers


  1. exports.get = async (req, res, next) => {
      categories=req.body.categories  // is like [_1234464 , 987654321] ;
     const filteredProducts= productModel.find({ categories:{$in:categories}  })
    })
    
    Login or Signup to reply.
  2. 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}: {}  })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search