0

The request (req.query) I got has this format:

{ duration: { gte: '5' }, difficulty: 'easy' }

To make it work in MongoDB, the final result should be as below

{ duration: { $gte: 5 }, difficulty: 'easy' }

This is the code I'm using

const queryObj = { ...req.query };
let queryStr = JSON.stringify(queryObj);
queryStr = queryStr.replace(/\b(gte|lte|gt|lt)\b/g, (match) => `$${match}`);

However, the output is { duration: { '$gte': '5' }, difficulty: 'easy' } so it didn't work.

{ duration: { $gte: 5 }, difficulty: 'easy' } : return every matched records
{ duration: { '$gte': '5' }, difficulty: 'easy' }: return 0 record.

My question is: How can i remove the '' sign so it can be used for query string?

0

1 Answer 1

1

The regex approach won't work with converting numbers as a regex is binding you to stay with string. You're going to have to iterate over the entire object and check each key.

Here is a very simple recursive function that achieves this:

let finalObject = { duration: { gte: '5' }, difficulty: 'easy' }

function recursivelySearchObject(object) {
    if (typeof object === "string") {
        if (/^\d+$/.test(object)) {
            return parseInt(object)
        } else {
            return object
        }
    } else {
        Object.keys(object).forEach((key) => {
            object[key] = recursivelySearchObject(object[key]);
        });
        return object
    }
}

recursivelySearchObject(finalObject);

You can skip the recursive aspect if the object will always be "shallow" and just check to a certain depth using a for loop instead.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, it worked! By the way, I'm still puzzled at why the query string with ' ' didn't work. Is this expected?
I'm not sure what you mean by query string but Mongo expects a number for $gte. it doesn't validate and sanitize input.
I edited my question with a bit more information. Basically, I tried 2 different query string in Mongo DB Atlas filter.
So the problem is again with the 5, Mongo can receive key names without " or ' around them as-long as you're not using the dot notation, but as i mentioned $gte expects a number in this context. otherwise is trying to compare strings and your field is not string type.
Ah I see!! Thank you, Tom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.