如果我事先不知道我可能从客户端收到多少查询字符串,如何通过多个查询参数过滤结果?

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

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

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

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

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

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

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

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

或 可能是

localhost:5000/admin/customers?no_of_items_purchased=15

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

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

但我想要的是对从查询参数接收到的任何内容使用 .find 函数。像一个通用的代码来实现这个。

PS: 也请帮忙: "How to filter req.query so it only contains fields that are defined in your schema ?"

您可以创建一个 query 变量来保留要过滤的字段。

假设您的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);

只需将 request.query 作为参数直接传递给 find 方法:

Customer.find(request.query)