Running Queries from JavaScript
Queries are stored in view variables, just like any other variable. A query is defined as an object variable, with the
attribute array="true"
.
Example:
Listing All Objects
To query all members, use DB.person.all()
:
Listing All Objects in a Relationship
To query all members in a household, do a lookup through the household (remember that we defined the name of the relationship as "members"):
Note that the result of a query is a Query object, not a regular array. The query is automatically re-evaluated when the view is reloaded.
Counting Results
To determine the number of results returned by a query, use its count()
function:
Filtering
Queries may be filtered, using the where
function:
To find a single object, use get
:
Note that if multiple objects match the query with get, an arbitrary one is returned.
Filtering may be performed on multiple attributes by combining them with and
or or
, for example:
On numbers, any of the = != > < >= <=
operators may be used. Complex conditions may also be constructed with
parentheses.
String matching is possible - always case insensitive:
Relationships may also be filtered further:
Queries may be chained - internally this combines the individual parts with and
:
Sorting
Queries may be sorted by one or more attributes:
Limiting Results
limit()
is undefined, please ensure that you've upgraded to version 3.7.5 or later if you are using Android.You can limit the maximum number of results returned by a query using the limit()
function as shown below:
Deleting
All objects in a query can be deleted from the database with destroy_all
:
Looping Through Objects
Calling fetch()
on a query returns a normal JavaScript array that you can use to loop through objects:
If an object is modified in a loop, it must be saved manually: