'How Do I Make a Multi-filter Search?
I'm building an ecommerce site with Vanilla JS, Node and MongoDB. My search bar currently can only return searches based upon the name of the product as follows:
productRouter.get('/', expressAsyncHandler(async (req, res) => {
const searchKeyword = req.query.searchKeyword
? {
name: {
$regex: req.query.searchKeyword,
$options: 'i'
}
}
: {};
const products = await Product.find({...searchKeyword});
res.send(products);
})
);
I've tried adding category and brand inside of the ? {} like so to no avail:
? {
name: {
$regex: req.query.searchKeyword,
$options: 'i'
},
category: {
$regex: req.query.searchKeyword,
$options: 'i'
},
brand: {
$regex: req.query.searchKeyword,
$options: 'i'
}
}
Thanks!
Solution 1:[1]
You could use the search text feature.
It would be something like this:
// Creating compound index on db
db.product.createIndex({ name: 'text', category: 'text', brand: 'text' })
// Executing query
db.product.find({ $text: { $search: "something" } })
If you're using Mongoose, here is demonstrating how to create an index.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arthur Medeiros |
