【发布时间】:2022-01-19 18:53:52
【问题描述】:
我想根据输入变量创建一个动态的 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 '';
};
但它没有任何帮助
【问题讨论】:
-
你想动态构建一个object/array结构,不是字符串。是的,完全可以动态创建对象并放入数组…