首页 > 解决方案 > 过滤时出现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 });
    }

标签: node.jsjsonfiltering

解决方案


要正确替换它,您应该使用以下内容:

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)


推荐阅读