How to Search the Database by Date From Server-side JavaScript


Searching or querying a database is one of the most common actions in a mobile app. platform provides a cloud database to store any app data and Server Code that allows to write any server-side app logic using JavaScript. Server Code has an API to query the database that makes it easy to perform search queries based on a date. In this blog post you will learn how to write a script to query a database collection using dates.

To start, we need to create a sample database collection. Our collection looks like this:

Database collection

Database collection

The collection has two built-in date columns:

  • _createdAt – the time when a record was created
  • _updatedAt – the time when a record was updated (default value is set to _createdAt)

and two custom columns, both are of Date type:

  • startTime
  • endTime

You can of course include any other data.

Now let’s get to the code.

The first code examples shows how to query by using the built-in fields (_createdAt or _updatedAt).

This search query will return all objects where the _updatedAt date is less then ($lt) the current time (when the script runs).

When using one of the built-in data types in a query (_createdAt, _updatedAt), the date value must be formatted in ISO format. When using a custom column with Date type, using ISO format is not required.

The next code examples uses a custom endDate column (type Date). Note that the syntax to use the built-in date column (above) and a custom column is slightly different:

This query returns all records where the endTime is less than December 31, 2016. Based on data in the collection, only the record that contains tablets will be returned. This is how the response looks:

Let’s now look at another code example where we will use the startTime and endTime together.

In the following code snippet we query for all objects where the startTime is greater than December 31, 2016 and the endTime is less then February 1, 2017.

Querying the database by dates or any other columns is best suited for server-side logic as you can test the script and ensure it works before using in an app. Moving this logic to the client would only complicate the app and make it more error prone.

Once the Server Code script is tested and read you can import the service API for it inside the App Builder. This short video shows how to import a backend service. To learn more about Server Code, watch the Server Code YouTube playlist videos.