如果我事先不知道我可以从客户端收到多少个查询字符串,如何通过多个查询参数过滤结果? [英] How to filter results by multiple query parameters if I don't know beforehand how many query strings I may receive from client side?

查看:89
本文介绍了如果我事先不知道我可以从客户端收到多少个查询字符串,如何通过多个查询参数过滤结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据客户端发送的查询参数(使用猫鼬的.find函数)进行搜索,以发送一些数据作为响应.我需要做的是根据收到的参数进行搜索?

I want to send in response some data according to searching by query parameters (using .find function of mongoose) from the client side. What do I need to do is a search according to the parameters received?

我的意思是: 我可能会收到

What I mean is : I may receive

localhost:5000/admin/customers?customer_id=1&customer_email=abc@gmail.com

我本可以使用此代码根据此查询发送结果:

I could have used this code to send results according to this query :

Customer.find({
  customer_id = req.query.customer_id,
  customer_email = req.query.customer_email,
}, (err,docs)=> {
    res.json(docs);
})

或 只是

localhost:5000/admin/customers?customer_id=1

我本可以使用此代码根据此查询发送结果:

I could have used this code to send results according to this query :

Customer.find({
  customer_id = req.query.customer_id
}, (err,docs)=> {
    res.json(docs);
})

或 可能是

localhost:5000/admin/customers?no_of_items_purchased=15

我本可以使用此代码根据此查询发送结果:

I could have used this code to send results according to this query :

Customer.find({
  no_of_items_purchased = req.query.no_of_items_purchased
}, (err,docs)=> {
    res.json(docs);
})

但是我想要对从查询参数接收到的任何东西使用.find函数.就像实现此目的的通用代码.

But what I want is to use .find function on anything received from query params. Like a general code to achieve this.

PS:另外,请提供以下帮助:如何过滤req.query,使其仅包含架构中定义的字段?"

PS: Also please help with : "How to filter req.query so it only contains fields that are defined in your schema ?"

推荐答案

您可以创建query变量以保留要过滤的字段.

You can create a query variable to keep the field that you want to filter.

假设您的Customer模型结构为:

{
  customer_id: ...,
  customer_name: ...,
  customer_email: ...,
  no_of_items_purchased: ...
}

然后您的代码将是:

let {customer_id, customer_name, customer_email, no_of_items_purchased} = req.query;
let query = {};
if (customer_id != null) query.customer_id = customer_id;
if (customer_name != null) query.customer_name = customer_name;
if (customer_email != null) query.customer_email = customer_email;
if (no_of_items_purchased != null) query.no_of_items_purchased = no_of_items_purchased;
let result = await Customer.find(query);

这篇关于如果我事先不知道我可以从客户端收到多少个查询字符串,如何通过多个查询参数过滤结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆