繁体   English   中英

如何根据查询参数搜索猫鼬?

[英]How can I search in mongoose according to my query parameters?

我有一个表单,用户可以通过指定买家名称或商品名称或两者都选择来搜索交易,因此我可以使用以下任何查询:

本地主机:8000 / allPayments /?i = pasta
本地主机:8000 / allPayments /?b = Youssef
本地主机:8000 / allPayments /?b = Youssef&i = pasta

在下面的代码中,猫鼬将始终寻找它们两者

 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次不同的时间编写上面的代码? 例如:如果查询是第二个查询,则仅执行find({'buyerName':req.query.b})

您可以先根据条件创建查询对象,然后再使用该查询对象。 喜欢 :

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM