Dojo FAQ: How do I query a store using complex criteria (age > 25)?

By on October 9, 2013 8:04 am

Dojo stores provide a simple and powerful way to interact with data via widgets or any other data consumer. Two stores that come with The Dojo Toolkit are dojo/store/Memory and dojo/store/JsonRest. Both of these stores have a query method, which will return query results that match certain criteria. A simple query may look something like this:

    name: "John"

This would query the store for any objects that had a name of "John" and return those items.

You may be asking yourself, “Is it possible to do more complex queries? Say, finding a number greater than some value?”  The answer is that the capabilities of your query syntax are dependent on the data provider backing your store.  For example, if you’re using dojo/store/JsonRest then the complexity of your queries are limited by the query syntax your server implements. It’s possible to devise a query language that is very expressive but quite often server-backed stores are limited to fairly simple key-value queries. However, if you’re using dojo/store/Memory or any store that uses SimpleQueryEngine you can easily handle more complex queries.

One type of query supported by SimpleQueryEngine allows you to pass a function to the query method of the store. This function will receive each object from the store, and should indicate if the object is to be included in the QueryResults by returning true or false for each object.

Let’s take a look at an example. To query for all users who are older than 25, you can do something like this:

users.query(function (user) {
   return user.age > 25;

And that’s it! Using complex criteria to query a store that uses SimpleQueryEngine is easy when you pass a function to the query method.