0

I am trying to create a mongoDB query but the conditional is set as a string and the output is returning a blank array. Here is an example of what I'm tyring to do:

    let sample_text = "{$and: [some conditions]}"
    let results = My_Collection.find(sample_text).fetch()

This will result in a an empty array. But if I manually enter the regex query like this I get an array with the values I'm expecting:

    let results = My_Collection.find({$and: [some conditions]}).fetch()

The sampe text regex string is being generated by an outside funciton and is being returned as a string.

My question is how can I insert my regex string without the quotations? Or is there a better way to generate the regex without making it a string in the first place?

I have tried using new RegExp but that destroys some of my expressions, and I have tried to simply remove the quotations as the first and last character but that doesn't work either.

Edit: Cannot simply turn query into a JSON object since it contains special characters such as $.

kips
  • 17
  • 2
  • 8
  • Possible duplicate of [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – dnickless Aug 14 '18 at 19:38
  • due to the $ symbol the query cannot be turned into a JSON object – kips Aug 14 '18 at 19:42
  • You might need to replace some bits: https://stackoverflow.com/questions/40649789/json-parse-error-with-dollar-in-key – dnickless Aug 14 '18 at 19:44
  • Yes that worked. I just had to add double quotes around each objectID – kips Aug 14 '18 at 20:12

1 Answers1

0

If I understand your question properly, you are: getting a text string from an external source that is a string representation of your query.

Passing the string into MongoDB will not work, because MongoDB takes an object as input.

You will need to convert the string to an object. Ideally, the string passed in is JSON. But the string you present is not JSON. An example JSON version would be:

sample_text = "{"$and":[{"foo":true},{"bar":false}]}"

Then you could produce the object by running JSON.parse(sample_text):

let sample_text = "{"$and":[{"foo":true},{"bar":false}]}";
let query = JSON.parse(sample_text);
let results = My_Collection.find(query).fetch();
BruceJo
  • 591
  • 6
  • 17