[英]How Do I Make a Multi-filter Search?
I'm building an ecommerce site with Vanilla JS, Node and MongoDB.我正在用 Vanilla JS、Node 和 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!谢谢!
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.如果您使用的是 Mongoose,这里将演示如何创建索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.