我想根据客户端的查询参数(使用 mongoose 的 .find 函数)搜索来发送一些数据作为响应。我需要做的是根据收到的参数进行搜索吗?
我的意思是: 我可能会收到
localhost:5000/admin/customers?customer_id=1&[email protected]
我可以使用此代码根据此查询发送结果:
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:还请帮忙:“如何过滤 req.query,使其仅包含您的架构中定义的字段?”
您可以创建一个
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)
export function getStrictQueryClause (input) {
let clauses = []
const clauseValues = [];
console.log(input)
Object.entries(input).forEach(([key, value]) => {
if (value) {
clauses.push(`AND ${key} = ?`)
clauseValues.push(value)
}
})
const clause = clauses.join(' ')
返回{子句,子句值};
对于使用mysql2和javascript的人,您还可以使用此函数生成子句并将其连接到sql查询。我认为这会更容易使用并避免进一步的 sql 注入。
From: http://localhost:3100/theorems?author=Euclides&field=algebraic-topology
Input: {author: "Euclides", field: "algebraic-topology"}
Output: {
clause: 'AND author = ? AND field = ?',
clauseValues: [ 'Euclides', 'algebraic-topology' ]
}