JavaScript

Javascript - Perform CRUD operations using Parse

Introduction

This section explains how to implement the CRUD (Create, Read, Update and Delete) operations in a javascript environment through Back4App.

We’ll also provide 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 knowing basic javascript.

Optional: To complete this tutorial using your own app, you will need:

  • An app created and configured for javascript at Back4App.

Step 1 - Configuring the environment

We are going to use the JSbin platform to be our code editor. It is very easy to start using: just open their 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 is already created so that you can check your changes on the database without having to create your own.
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/parse@1.10.0/dist/parse.min.js"></script>

Then add your your credentials in the beginning of the javascript file. The default keys are the one 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, which has a name and an age fields, where name is a string and age is a number. Because of that, our code should start by creating a subclass of the Pet class so that it can be used later in our functions.

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 is also a good idea to create a textAge one, which will be used in the 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 function “set” 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 Back4App Javascript Create Function to see to code already implemented.

The code for the create function can be found 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. If it worked 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 the object that matches your search criteria. It can also be used to check the existence of a object. The step by step to build your own read function is as follow:

  1. Make a instance of the Parse’s Query class;
  2. add constraints to you 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 succeeded, a pet object is returned;
  5. if no object is found, the return object has the value ‘undefined’;

You can open Back4App Javascript Read Function to see to code already implemented.

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 or that no pet was found.
If 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 then. So, what is happening is another user has already created a object with that name and with a different age. Your query is returning that object.
So, to really test the read function, create a 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 provide in the textAge variable. To find the pet which will be passed, we use a modified version of our read function. Next, there is the steps to make your own update function:

  1. Write a modified read function, 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 Back4App Javascript Update Function to see to code already implemented.

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 this code 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 that the age of the object has changed by calling your read function again.

Step 5 - Delete

The delete function erases a pet received by a read function. It is an irreversible action, which means that you should be careful when using it, especially because your read function might return more objects than you want to delete. We recommend using only deleting one object per time for safety reasons. The steps to write 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 Back4App Javascript Delete Function to see to code already implemented.

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);
        }
    });
}

For testing, is 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 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 happen, probably means that you have more objects with the same same and it returned one of then (the delete function just deletes one object). You can check your object by accessing your Parse Dashboard.

Next Steps

At this point, you have learned how to do the basic CRUD operations with JavaScript. You are now ready to explore Parse Server core features and Back4App add-ons.

Learn more by walking around Parse open source documentation for JavaScript SDK.