node.jsexpressmongoosequery-stringquerystringparameter

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


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 ?"


Solution

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