JavaScript

Performing Serverless Database Operations

Introduction

This section explains how to implement the CRUD (Create, Read, Update and Delete) Operations in a JavaScript environment through Back4App. It also provides code snippets and an online environment to execute and test your code with no local setup.

See more about Parse SDK at JavaScript SDK API Reference and Parse open source documentation for JavaScript SDK.

Prerequisites

There are no additional requisites other than having the basic knowledge of JavaScript.
Optional: To complete this tutorial using your own app, you will need:

Step 1 - Set up the environment

This guide uses the JSbin platform as a code editor. It’s very easy to use, all you need to do is open its main page and click on the HTML, JavaScript and Console buttons:

JavaScript_CRUD_WebPage

The first step to start coding is to include the Parse API and to add your App’s keys.
For this tutorial, a public Back4App app has been created so that you can check your changes on the database without having to create your own app.

Optional: To check the Parse database for this example, you need to create your own app and access the Parse Dashboard option.

To include Parse API in your app, add the following line of code inside the HTML’s head tag:

1
<script src="https://npmcdn.com/[email protected]/dist/parse.min.js"></script>

Then add your your credentials in the beginning of the JavaScript file. The default keys are the ones related to our public app.

1
2
3
Parse.initialize("JfMeozLs8UZFxaZibAiZhlpDl5OZkyjVwzdxLfqw"); //PASTE YOUR Back4App APPLICATION ID
Parse.JavaScriptKey = "fi6LWURzRGmTg7neZfI79MJaB2QHjWhiZ4nVFvKD"; //PASTE YOUR JavaScript KEY
Parse.serverURL = "https://parseapi.back4app.com/";

In this tutorial, we will build the CRUD Operations based on a Pet class that has a name and an age fields, in which name is a string and age is a number. Because of that, the code should start by creating a subclass of the Pet class so that it can be used later in our functions, as shown below:

1
var Pet = Parse.Object.extend("Pet");

All of the basic operations will require the user to say what is the desired Pet’s name. That way, create a global variable “textName”. It’s also a good idea to create a “textAge” one, which will be used in create and update methods.

1
2
var textName = "myName";
var textAge = 10;

Step 2 - Create

The create function will create a new Pet with the name and age that you provided in the “textName” and “textAge” variables.

To build that function, just follow these steps:

  1. Make a new instance of the Parse’s Pet class with the command new Pet().
  2. Use the set function to set the parameters for this object.
  3. Call the save function, which will effectively register the pet to your database in the Parse Dashboard.

You can open the Back4App JavaScript Create Function to see the code that has already been implemented.

The code for the create function is written below:

create.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
create();

function create() {
    mypet = new Pet();
    mypet.set("name", textName);
    mypet.set("age", textAge);

    mypet.save(null, {
        success: function (pet) {
            console.log('Pet created successful with name: ' + pet.get("name") + ' and age: ' + pet.get("age"));
        },
        error: function (response, error) {
            console.log('Error: ' + error.message);
        }
    });
}

To test it, paste this code snippet in the JavaScript file in the JSbin, click on the Run button in the console part and wait for the output.
It should print that the pet was created successfully. To confirm that the new object is in the database, you can access the Parse Dashboard or you can code the read function.

Step 3 - Read

The read function is responsible for querying the database and returning the object that matches your search criteria. It can also be used to check the existence of an object.
Here’s the step-by-step guide for building your own read function:

  1. Make an instance of the Parse’s Query class.
  2. Add constraints to your query to restraint the search. More constraints options can be found in Parse Query Documentation.
  3. Do a Query’s search method. This tutorial will use query.first to get only the first element that matches your criteria.
  4. If the operations succeed, a pet object will be returned. If no object is found, the return object will have an value of undefined.

You can open the Back4App JavaScript Read Function to see the code that has already been implemented.

The code for the read function is the following:

read.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
read();

function read() {
    query = new Parse.Query(Pet);
    query.equalTo("name", textName);
    query.first({
        success: function (pet) {
            if (pet) {
                console.log('Pet found successful with name: ' + pet.get("name") + ' and age: ' + pet.get("age"));
            } else {
                console.log("Nothing found, please try again");
            }
        },
        error: function (error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    });
}

To test the read function, paste the snippet to your JSBin JavaScript file. When the code runs, it will print the age of the pet found (if found) or else will print that no pet was found.

If while testing the printed age does not correspond to the age of your object, it means that there are more objects with the same name, but your query only returns one of them. So, to really test the read function, create an object with another name, one that no one has created yet, then run the function, which will correctly print the age of the object.

Step 4 - Update

For the update function, a pet is passed as parameter and the function changes it’s age to the one you provided in the “textAge” variable. To find the pet which will be passed, we use a modified version of our read function.

Below are the steps to make your own update function:

  1. Write a modified read function called readThenUpdate, which calls the update function when it finds a pet successfully.
  2. In the update function, use the set function to modify the parameters of your pet.
  3. Call the save function for this pet to push the changes to the database.

You can open the Back4App JavaScript Update Function to see the code that has already been implemented.

Here’s the code for the readThenUpdate function and update function:

update.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
readThenUpdate();

function readThenUpdate() {
    query = new Parse.Query(Pet);
    query.equalTo("name", textName);
    query.first({
        success: function (pet) {
            if (pet) {
                console.log('Pet found with name: ' + pet.get("name") + ' and age: ' + pet.get("age"));
                update(pet);
            } else {
                console.log("Nothing found, please try again");
            }
        },
        error: function (error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    });
}

function update(foundPet) {
    foundPet.set('name', textName);
    foundPet.set('age', textAge);

    foundPet.save(null, {
        success: function (pet) {
            console.log('Pet updated! Name: ' + pet.get("name") + ' and new age: ' + pet.get("age"));
        },
        error: function (response, error) {
            console.log('Error: ' + error.message);
        }
    });
}

To confirm if the update function is working, paste the code above to the JavaScript file in the JSBin page.
Use an unusual name for your object to not conflict with other users, then follow these steps:

  1. Create an object with your desired name.
  2. Check that the object is created with your read function.
  3. Call your readThenUpdate function made in this topic with an age different than the original one.
  4. Check if the age of the Pet has changed by calling your read function again.

Step 5 - Delete

The delete function erases a pet received by the read function. It is an irreversible action, which means that you should be careful while using it, especially because your read function might return more objects than you actually want to delete. Because of that, it’s recommended to delete only one object at a time. The steps for writing your own delete function can be found below:

  1. In the end of the success of your “read” function (readThenDelete in this example), make a call for the delete function.
  2. In the deletePet function, call the destroy method on the received object “foundPet”.

You can open the Back4App JavaScript Delete Function to see the code that has already been implemented.

Here’s the code for the readThenDelete function and deletePet function:

delete.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
readThenDelete();

function readThenDelete() {
    query = new Parse.Query(Pet);
    query.equalTo("name", textName);
    query.first({
        success: function (pet) {
            if (pet) {
                console.log('Pet found with name: ' + pet.get("name") + ' and age: ' + pet.get("age"));
                deletePet(pet);
            } else {
                console.log("Nothing found, please try again");
                return null;
            }
        },
        error: function (error) {
            console.log("Error: " + error.code + " " + error.message);
            return null;
        }
    });
}

function deletePet(foundPet) {
    foundPet.destroy({
        success: function(response) {
            console.log('Pet '+ foundPet.get("name") + ' erased successfully');
        },
        error: function(response, error) {
            console.log('Error: '+ error.message);
        }
    });
}

To test it, it’s recommended to create an object with an unusual name just like the other functions to not conflict with objects from other users.
Just paste the snippet to the JSBin and run the code with the name of your object and the object that will be deleted.
Then, you can call your read function to confirm that there are no objects with that name.

If the read returns an object, which it shouldn’t, it probably means that you have more objects with the same name and it returned one of them as the delete function just deletes one object.
You can check your object by accessing your Parse Dashboard.

It’s done!

At this point, you have learned how to do the basic CRUD operations with JavaScript.