我想根據輸入變數創建一個動態 MongoDB 查詢, 我嘗試將查詢作為字串,但它不起作用。
let carsPromise = Car.find({
carsFetchQuery(company, model, minPrice, maxPrice),
})
.skip(offSet)
.limit(rowsPerPage)
.lean();
如果輸入引數不為空,則動態創建獲取查詢的函式
const createCarFetchquery = (company, model, minPrice, maxPrice) => {
if (
company === null &&
model === null &&
minPrice === null &&
maxPrice === null
)
return '';
let query = `$and: [
{
$or: [{
${getQuery('$eq', 'company', company)} ${model ? ',' : ''}
${getQuery('$eq', 'model', model)} ${minPrice ? ',' : ''}
${getQuery('$gte', 'minPrice', minPrice)} ${maxPrice ? ',' : ''}
${getQuery('$eq', 'maxPrice', maxPrice)}
}],
},
]
`;
獲取查詢運算式的輔助函式
const getQuery = (opertor, key, value) => {
if (value) {
return `${key}: {${opertor}: '${value}'}`;
}
return '';
};
但它沒有任何幫助
uj5u.com熱心網友回復:
您不能將字串注入查詢,但您可以在查詢中傳遞一個物件,準備一個物件陣列并在查詢中使用它,
為了理解我已經更新了您的方法如下,您可以根據您的要求進行更改,
const createCarFetchquery = (company, model, minPrice, maxPrice) => {
let query = [];
if (company) query.push(getQuery('$eq', 'company', company));
if (model) query.push(getQuery('$eq', 'model', model));
if (minPrice) query.push(getQuery('$gte', 'minPrice', minPrice));
if (maxPrice) query.push(getQuery('$eq', 'maxPrice', maxPrice));
if (query.length) return { $or: query };
return {};
}
const getQuery = (opertor, key, value) => {
return { [key]: { [opertor]: value } };
};
console.log(createCarFetchquery("ABC", "A", 10, 12));
并在您的查詢中使用它,但請確保您已通過 async/await 方法包裝您的查詢,
let carsPromise = await Car.find(
carsFetchQuery(company, model, minPrice, maxPrice)
)
.skip(offSet)
.limit(rowsPerPage)
.lean();
uj5u.com熱心網友回復:
find需要一個 JSON 物件,因此它可以與
let carsPromise = Car.find(
JSON.parse(carsFetchQuery(company, model, minPrice, maxPrice))
)
這對于 NoSQL 注入非常脆弱。
更好的方法是這樣的:
var query = []
var field = {}
field['company'] = {}
field['company']['$eq'] = company
query.push(field)
var field = {}
field['minPrice'] = {}
field['minPrice']['$gte'] = minPrice
query.push(field)
// or a bit shorter (thanks to turivishal)
query.push({ ['maxPrice']: { ['$eq']: maxPrice} })
let carsPromise = Car.find({$and: [ { $or: query } ] })
您只需使用回圈推送任意數量的條件。但是,仍然可以注入 NoSQL 代碼,例如當 URL 如下所示時:
...?model['$ne']=null
那么查詢將回傳所有model不為空的檔案- 很可能是所有檔案,請參閱https://blog.websecurify.com/2014/08/hacking-nodejs-and-mongodb.html
因此,您應該使用mongo-sanitize或類似方法保護輸入值:
field['company']['$eq'] = sanitize(company)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419444.html
標籤:
下一篇:檢查R資料框中每個變數的資料型別
