Having trouble converting a complex javascript object to a query string Having trouble converting a complex javascript object to a query string express express

Having trouble converting a complex javascript object to a query string


I am using this code in production for querying against a server with a MongoDB backend (using angular and lodash):

.factory('mongoQuery', function() {  return {    fromJson: function(json) {      return JSON.parse(json, fromJsonReviver);    },    toJson: function(object) {      return JSON.stringify(object, toJsonReplacer);    }  };  function fromJsonReviver(key, value) {    var val = value;    if (_.isPlainObject(value)) {      if (_.isNumber(value.$date)) {        val = new Date(0);        val.setUTCMilliseconds(value.$date * 1000);      } else if (_.isString(value.$regexp)) {        var match = /^\/(.*)\/([gimy]*)$/.exec(value.$regexp);        val = new RegExp(match[1], match[2]);      }    }    return val;  }  function toJsonReplacer(key, value) {    var val = value;    if (_.isPlainObject(value)) {      val = _.extend({}, value);      for (var k in value) {        val[k] = toJsonReplacer(k, val[k]);      }    } else if (_.isDate(value)) {      val = {$date: (new Date(value)).valueOf() / 1000};    } else if (_.isRegExp(value)) {      val = {$regexp: value.toString()};    }    return val;  }})

It includes many of the suggestions mentioned by others in the comments and supports dates and regular expressions.

Other than that, if you need to send the query with a GET request, just use encodeURIComponent like others have mentioned.

Here is a working example: http://plnkr.co/edit/b9wJiUkrHMrDKWFC1Sdd?p=preview


What you're thinking here is basically to redevelop an API server, coupled with some mongodb database, and querying it with some format.

  1. REST is the "best practise" you're looking for. It's a standard that encapsulates some common actions to http ressources.
  2. You should know that you don't need to redevelop an ecosystem based on such a standard. Full-featured REST API servers exist, some are even based on express.js. Loopback and sails.js. These one provide some extra features like
    • Model abstraction through ORM's, and database-engine agnostism
    • Automatic REST actions, from database schema or model finition
    • Advanced querying through "extended REST" ("where", "limit", "order", ...)
    • Realtime with REST-like websockets
    • Client side libraries that help you query the server
  3. Some standalone exernal libraries, such as js-data or Restangular can deal with REST server pretty well, and act as a frontend connector to backend

Now, if I had to purely answer your question, and if you realy wanted to go with your solution, I'd just add the mongo query to a where query param on the http call with encodeURIComponent as stated before.