MongoDB The value given .... must be valid JSON

2023-04-25 MongoDB: The value given must be valid JSON.

I'm really struggling with something that should be simple and have tried to simplify the code as much as possible in order to fix, but I'm stuck.

Step 1

I have a MongoDB query called "queryDirectTest" that works fine:

{ "GENDER_label" : "Women" }

Step 2

I need to build conditional logic to create more advanced and/or queries, so I have built a transformer called "mongoDBTransformerTest"

let query = '{ "GENDER_label" : "Women" }'
return query

When I preview the transformer, I get the message Transformer ran successfully and the result "{ "GENDER_label" : "Women" }"

Step 3

However, when I try to pass this to a MongoDB query called "queryTransformerTest" using

{{ mongoDBTransformerTest.value }}

I get the message The value given - { "GENDER_label" : "Women" } must be valid JSON.

I have tried every trick I can think of to get this to work including JSON.parse(), JSON.stringify, Object() and others and cannot get this to work, even with this very simple JSON string.

I've noticed others having similar problems - MongoDB - 'Must be valid JSON' Error and [MongoDB] parsing json error and tried to fix, but without success.

Any assistance would be much appreciated!

Finally, was able to solve it with a little help from Google Bard :slight_smile:

In case anyone else is running into this problem, this code in my "mongoDBTransformerTest" did the trick:

let query = '{ "GENDER_label" : "Women" }';
let queryObject = JSON.parse(query);
return queryObject;

Basic stuff, I realize, but just getting started in Retool, so thought I would pass on the insight.

Hey @MatthewFass!

Glad you were able to find a solution here :grin: if it's a bit easier, you should also be able to return the object directly as long as you don't wrap it in quotes. Does something like this work?

let query = { "GENDER_label" : "Women" }
return query

@Kabirdas Thank you for that!

Being relatively new to JS, I realized I needed to brush up on objects. I've simplified the whole thing down to

const genderFilterValues = {{ genderFilter.value }}
const query = {
    GENDER_label: { $in: genderFilterValues }
};
return query;
1 Like