Moving App Logic to the Server: How to Query the Database From Server Code Script

An Appery.io developer posted a question on the Appery.io Facebook page on how to write a Server Code script to query two different collections in the database. This post will show you how to do that.

In general, querying two database collections is better to do on the server-side than from the client. Doing it on the server is a lot faster and provides you with the option to update the search without impacting the client. Plus, you can add any logic when needed. Doing it from the client would require two REST API calls to the database.

Let’s jump into the example.

First, there are two collections in the Appery.io Database. They look like this:

ProductName collection:

ProductName collection.

ProductName collection.

This collection is simple. It has a name and a code.

This is the ProductData collection:

ProductData collection.

ProductData collection.

 

The code in this collection links the product name to the actual product (Android or iOS device).

The input to the script is the product type: Android or iOS. Based on the input, you lookup the code for the product (a or i) and then run a second query to find all iOS or Android phones in the ProductData collection. Here is the script.

var product = request.get("type");
var dbId = "367e9e77......";
var params = {};
var result = [];

// Search for object with the provided 'type' (iOS or Android)
params.criteria = {
   "name": {
      "$eq": product
   }
};
result = Collection.query(dbId, "ProductName", params);

// Find all objects with code 'i' or 'a'
params.criteria = {
   "code": {
      "$eq": result[0].code // Either 'i' or 'a'
   }
};
// Run the query
result = Collection.query(dbId, "ProductData", params);
// Script response (API response)
Apperyio.response.success(result, "application/json");

This script first searches the ProductName collection to find the id for iOS or Android devices. Then it searches the ProductData collection to find the actual devices.

Moving this logic to the server is a good idea as you query two collections (or even more) with a single request from the client.

If you want to learn more about Server Code, check out our YouTube channel Server Code playlist.