[英]Create query based on inputs from user
So lets say I am running a search through the database所以可以说我正在通过数据库进行搜索
router.post('/searchLoads', ensureAuthenticated, async (req, res) => {
var{ agentCode, loadNumber, pickupNumber, pickupDate } = req.body});
The user is not required to fill out all fields.用户无需填写所有字段。 How would I build a query based on if statements?
我将如何基于 if 语句构建查询? I was trying something along the lines of
我正在尝试类似的东西
result = 'await Load.find({';
if (agentCode !== undefined){
result += "agentCode: agentCode, ";
}
if(loadNumber !== undefined){
result += "loadNumber: loadNumber, ";
}
if(pickupNumber !== undefined){
result += "pickupNumber: pickupNumber, ";
}
if(pickupDate !== undefined){
result += "pickupDate: pickupDate, ";
}
result += "})";
But I am not sure how to then run the code now that I've created the query.但是,既然我已经创建了查询,我不确定如何运行代码。 Is there an easier way to do this?
有没有更简单的方法来做到这一点?
Instead of creating a string, you could create an object.您可以创建一个对象,而不是创建一个字符串。
Assuming we are using ES6+ we can use agentCode
instead of agentCode: agentCode
while initializing fields.假设我们使用 ES6+,我们可以在初始化字段时使用
agentCode
而不是agentCode: agentCode
。
var options = {
agentCode,
loadNumber,
pickupNumber,
pickupDate,
};
result = await Load.find(options);
The !== undefined
checks are not necessary, since undefined
fields will be dropped. !== undefined
检查不是必需的,因为undefined
字段将被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.