How to filter results by multiple query parameters if I don't know beforehand how many query strings I may receive from client side?

谁说我不能喝 提交于 2020-01-16 19:11:30

问题


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);
})

or just

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);
})

or may be

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);
})

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

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


回答1:


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

Suppose that your Customer model structure is:

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

Then your code will be:

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);


来源:https://stackoverflow.com/questions/57001644/how-to-filter-results-by-multiple-query-parameters-if-i-dont-know-beforehand-ho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!