我有一个表单,用户可以通过指定买家名称或项目名称来选择搜索交易。所以我可以有任何这些查询:
本地主机:8000 / allPayments / I =面食
本地主机:8000 / allPayments / B =优素福
?本地主机:8000 / allPayments / B =优素福&安培; I =面食
在下面的代码中,mongoose将始终查找它们
router.get('/allPayments', function (req, res, next) {
Transaction.find({'buyerName':req.query.b , 'itemName':req.query.i})
.then(function (docsPay) {
res.render('allPayments', {
payments: docsPay
});
});
如何在不编写上述代码3次的情况下告诉mongoose只查找查询中传递的内容? 例如:如果查询是第二个,则只查找({' buyerName':req.query.b})
答案 0 :(得分:0)
您可以先根据条件创建查询对象。然后使用该查询对象。 喜欢:
var query = {};
var isParamPresent = false;
if( req.query.b != undefined && req.query.i != undefined ){
query['buyerName'] = req.query.b;
query['itemName'] = req.query.i;
isParamPresent = true;
}
else if ( req.query.b != undefined && req.query.i == undefined ){
query['buyerName'] = req.query.b;
isParamPresent = true;
}
else if (req.query.b == undefined && req.query.i != undefined){
query['itemName'] = req.query.i;
isParamPresent = true;
}
else{
isParamPresent = false;
// both are undefined, your logic
}
if( isParamPresent ){
Transaction.find(query).then(function (docsPay) {
res.render('allPayments', {
payments: docsPay });
//Further logic
}