我正在尝试简化我的SQL命令中使用的控制器,以根据特定条件过滤记录。我的尝试起作用,但有许多缺陷。最明显的是它不可扩展,因为随着时间的推移,我可能会添加更多的critera,第二个是我无法保留特定字段未定义并运行查询。我希望如果一个值未定义,它们不会添加到查询中。所有参数都作为查询参数附加,然后进行捕获和处理。
在查询中使用嵌套的If / Else:
var whereFilterObject = {};
if (req.query.blogDateStart && req.query.blogDateEnd && req.query.blogType) {
whereFilterObject = {
blogDate: {
$between: [req.query.blogDateStart, req.query.blogDateEnd]
},
type: req.query.blogType
}
} else if (req.query.blogDateStart && req.query.blogDateEnd) {
whereFilterObject = {
blogDate: {
$between: [req.query.blogDateStart, req.query.blogDateEnd]
}
}
} else if (req.query.blogType) {
whereFilterObject = {
type: req.query.blogType
}
} else {
limitAmount = {
limit: 10
}
}
Post方法的附加查询参数:
if (blogDateStart && blogDateEnd && blogDateEnd) {
res.redirect('/app?' + 'blogDateStart=' + blogDateStart + '&' + 'blogDateEnd=' + blogDateEnd + '&' + 'blogType=' + blogType);
} else if (blogDateStart && blogDateEnd) {
res.redirect('/app?' + 'blogDateStart=' + blogDateStart + '&' + 'blogDateEnd=' + blogDateEnd);
} else {
res.redirect('/app?' + 'blogType=' + blogType);
}
答案 0 :(得分:0)
在这种情况下,您不需要像这样做一个链。您可以单独检查每个查询参数(根据您的需要),只需根据需要设置对象密钥。
var whereFilterObject = {};
var hasDateConditions = (req.query.blogDateStart && req.query.blogDateEnd);
var hasType = req.query.hasOwnProperty('blogType');
if (hasDateConditions) {
whereFilterObject['blogDate'] = {
$between: [req.query.blogDateStart, req.query.blogDateEnd]
}
}
if (hasType) {
whereFilterObject['type'] = req.query.blogType;
}
if (!hasType && !hasDateConditions) {
limitAmount = {
limit: 10
}
}