davidgtonge / backbone_query

A lightweight query api for Backbone Collections
MIT License
378 stars 29 forks source link

Storing the query part in a db #11

Closed ericlbarnes closed 11 years ago

ericlbarnes commented 11 years ago

Maybe I am missing something obvious but I am trying to store the actual query part in a db as a saved search and then use it to filter the collection.

Following your example:

MyCollection.query(
    {tags: { $any: ["coffeescript", "backbone", "mvc"]}},
    {sortBy: "likes", order: "desc", limit:10, page:2, cache:true}
);

If I take the main part out:

{tags: { $any: ["coffeescript", "backbone", "mvc"]}},
{sortBy: "likes", order: "desc", limit:10, page:2, cache:true}

That isn't valid json. Do you have any better ideas on how to store this in a db to be used later?

I was trying to store something like the following and merge the two parts together but isn't very clean and never could get it to work well:

{"query": [{"$and": {"tags": {"$all": ["!1"]},"status": "waiting"}}],"sorting": [{"sortBy": "last_reply_at", "order": "desc"}]}

Here is an actual query that works directly just not parsing via parseJSON

{$and: {tags: { $all: ["!1"] } }}, {sortBy: "last_reply_at", order: "desc", status:"waiting"}
davidgtonge commented 11 years ago

Hi, I think the problem is you are trying to serialize both the query object and the options object. If you serialize them separately it will work, or you could put them into an array.

JSON.stringify({$and: {tags: { $all: ["!1"] } }});  
//returns "{"$and":{"tags":{"$all":["!1"]}}}"

JSON.stringify({sortBy: "last_reply_at", order: "desc", status:"waiting"}); 
// returns "{"sortBy":"last_reply_at","order":"desc","status":"waiting"}"

//A few example functions
saveQuery = function(query, options) {
  JSON.stringify([query, options]); 
};

runSavedQuery = function(queryStirng) {
  var queryArray = JSON.parse(queryString);
  MyCollection.query(queryArray[0], queryArray[1]);
};
ericlbarnes commented 11 years ago

@davidgtonge You rock! Thanks for that reply.