node.js - 过滤时出现NodeJS String.replace()问题
问题描述
我无法修改过滤参数
字符串.replace()
我可以从 URL 中获取过滤键作为对象,但它对我来说很糟糕。
过滤:{{URL}}/api/v1/bootcamps?averageCost[lt]=10000
当前格式: { averageCost: { lt: '10000' } }
从at: { averageCost : { $lt: '10000' } }
所以我尝试将其转换为字符串并替换该值。但该值可以是:lt, lte, gt, gte, in但它有一些问题,因为.replace()方法之后的行没有执行,当然 catch 块包含错误......
我的代码片段:
try {
console.log(req.query);
const queryStr = JSON.stringify(req.query);
console.log(queryStr); //thats the last thing I get
queryStr = queryStr.replace(
/\b(gt|gte|lt|lte|in)\b/g,
match => `$${match}`
);
console.log(queryStr); // I dont get this
const bootcamps = await Bootcamp.find();
res.status(200).json({
succes: true,
count: bootcamps.length,
data: bootcamps
});
} catch (err) {
return res.status(404).json({ succes: false });
}
解决方案
要正确替换它,您应该使用以下内容:
let queryStr = '{ "averageCost": { "lt": "10000" }, "test": { "gt": "12345"} }';
const regex = /\b(gt|gte|lt|lte|in)\b/g;
queryStr = queryStr.replace(regex, '$$' + "$1"); // <-- here is the correct replace
这将替换queryStr
为:
{ "averageCost": { "$lt": "10000" }, "test": { "$gt": "12345"} }
JSFiddle https://jsfiddle.net/c52z8ewr/
如果您需要返回对象,请执行JSON.parse(queryStr)
推荐阅读
- php - 修补 laravel 8,无法获得关系
- javascript - 使用 JS 在旧版浏览器中触发 KeyDown 事件
- microsoft-teams - Microsoft Teams - 自定义应用程序,无法加载网页/第二个选项卡
- python - 选择另一种语言后,用硒内容抓取的网页无法正确更新
- mysql - 使用 PERIOD_DIFF mysql 按月分组
- javascript - 如何使用 Javascript 监听 onsignal 网络推送通知事件?
- twilio - sip 在 twilio 中注册用户
- reactjs - 删除项目后状态数组变得未定义
- reactjs - 带有 React 的 Digital Ocean 上的“无效主机头”Kubernetes 集群
- python - Python输出异常