NodeJS String.replace() problem while filtering

Viewed 741

I can't modify the filtering parameter with

String.replace()

I can get the filtering keys from the URL as an object but its badly fromatted from me.

Filtering: {{URL}}/api/v1/bootcamps?averageCost[lt]=10000

Current format: { averageCost: { lt: '10000' } }

Right fromat: { averageCost: { $lt: '10000' } }

So I tried to convert it as a String and replace that value. But that value can be: lt, lte, gt, gte, in but it has some problem because the line after the .replace() method doesnt executed and of course the catch block cathes the error...

My code snippet:

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 });
    }
2 Answers

To replace it correctly you should use something like this:

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

This will replace queryStr with:

{ "averageCost": { "$lt": "10000" }, "test": { "$gt": "12345"} }

JSFiddle https://jsfiddle.net/c52z8ewr/

If you need the object back just do JSON.parse(queryStr)

You can also Try This

const queryCpy = { ...this.query };

    // console.log(queryCpy, 'before filter');


    console.log(queryCpy, 'after filter');

    let queryString = JSON.stringify(queryCpy);

    queryString = queryString.replace(
        /\b(gt|gte|lt|lte)\b/g,
        (rep) => `$${rep}`,
    );

    console.log(queryString, 'after filter');
Related