Rahul Saini
Rahul Saini

Reputation: 937

Object behaviour changed after assigned the variable

I have received a query/argument (matchQuery) from the client side through API. When I console this request.query.matchQuery.on the server side it gives me {"count":{"$gt":1}} this is good for me.

when I assign this argument on the other variable like this

var aggregateQuery = {
             $match: request.query.matchQuery
 }

and now I console aggregateQuery its returns

{ '$match': '{"count":{"$gt":1}}' }

its behavior gets changed. But I don't want to single quotes on the right side.

OUTPUT

{ '$match':{"count":{"$gt":1}}}

OR

{ $match:{"count":{"$gt":1}}}

OR

{ $match:{count:{$gt:1}}}

Upvotes: 0

Views: 34

Answers (1)

Mahdi Imani
Mahdi Imani

Reputation: 204

Best way to correct data that receive in serialized JSON is to parse it. JavaScript has JSON global object for facilitate JSON conversion and applied in application.

in your case evidence shows that request that came from client is like this:

  "{\"count\":{\"$gt\":1}}"

but in your framework changed to STRING

   typeof('{"count":{"$gt":1}}')    ==>   'string'

that is not object

for use request.query.matchQuery as java script object your may convert it to JavaScript Object. for more details refer to below example:

var aggregateQuery = {
   $match: JSON.parse(request.query.matchQuery)
}

Notice:

If you are not in STRICT MODE by adding

 "use strict"

you can execute your code with

 eval( code to be execute )

for examlpe

 eval(`var e = { '$match':` + '{"count":{"$gt":1}}' + `}`)

Upvotes: 1

Related Questions