1

I'm trying to make a MongoDb script that passes a variable name from an array of variables and then executes a query for that variable:

var continous = ['b', 'e', 'LBE']; //list of variables

continous.forEach(e => izracun(e));

function izracun(atr) {
    var query = '{ $group: { _id: "'+atr+'", avg: { $avg: "$'+atr+'" }, stdev: { $stdDevPop: "$'+atr+'" }, nonMissing: { $sum: 1 }}}';
    query=JSON.parse(query);
};

The query is constructed as a string, but when I try to JSON.parse it, I get the following error:

[js] uncaught exception: SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data...

Variable "query" has the following value before JSON.parse:

{ $group: { _id: "b", avg: { $avg: "$b" }, stdev: { $stdDevPop: "$b" }, nonMissing: { $sum: 1 }}}

What is wrong here, why do I get that JSON.parse error? I'm planning to use the query inside db.collection.aggregate()

2
  • 1
    Why do you construct a string query just to parse it to an object afterwards? Why don't you just use an object in the first place? Commented Jan 28, 2020 at 8:33
  • Do not parse , I think the object constructed should work as it is. Give a try Commented Jan 28, 2020 at 8:55

1 Answer 1

2

All keys must be surrounded by double quotes " to use JSON.parse without error

let queryString = '{ "$group": { "_id": "b", "avg": { "$avg": "$b" }, "stdev": { "$stdDevPop": "$b" }, "nonMissing": { "$sum": 1 }}}';
console.log(JSON.parse(queryString))

Note:- If you want to include Date or Regular Expression in your query, you need to use callback function with JSON.parse and convert it into desired Data type

So, it is better option to use Object instead of query String.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.