我的MERN应用程序被卡住了。我希望用户过滤产品的结果。用户应用的标准越多,结果应该越窄。例如,如果我应用过滤器男孩,有10个结果。然后我试着涂裤子,应该只有5个结果符合我想要的。但现在它不起作用了。这是代码,
exports.getProductsSearchResult = (req, res, next) => {
let query = {};
const productCategory = req.query.category;
const productSize = req.query.size;
const productGender = req.query.gender
if (productCategory !== undefined) query.category = productCategory;
if (productGender !== undefined) query.gender = productGender;
if (productSize !== undefined) query.size = productSize;
console.log('query', query)
Products.find(query).then(product => {
// console.log(product)
res.status(200).json(product)
}).catch(err => {
console.log(err)
})
}
在谷歌StackOverflow后,我发现了一个类似的问题并解决了我的问题。这是代码,现在,我没有看到任何错误。但如果有什么可以改进的地方,请告诉我。
exports.getProductsSearchResult = (req, res, next) => {
let query = {};
const productCategory = req.query.category;
const productSize = req.query.size;
const productGender = req.query.gender
let payload = { "category": productCategory, "size": productSize, "gender": productGender }
if (payload.category && payload.category.length > 0) query.category = { $in: payload.category }
if (payload.size && payload.size.length > 0) query.size = { $in: payload.size };
if (payload.gender && payload.gender.length > 0) query.gender = { $in: payload.gender };
console.log('query', query)
Products.find(query).then(product => {
// console.log(product)
res.status(201).json(product)
}).catch(err => {
console.log(err)
})
}