如何进行多过滤器搜索?



我正在用香草JS, Node和MongoDB建立一个电子商务网站。我的搜索栏目前只能返回基于产品名称的搜索结果,如下所示:

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);
})
);

我试过在?{} 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'
}
}

谢谢!

您可以使用搜索文本功能。

应该是这样的:

// Creating compound index on db
db.product.createIndex({ name: 'text', category: 'text', brand: 'text' })
// Executing query
db.product.find({ $text: { $search: "something" } })

如果您正在使用Mongoose,下面将演示如何创建索引。

最新更新