Blog

How to Use Backendless Atomic Counters to Create a Unique ID for Objects in a Table

by on March 12, 2019

Creating unique IDs using Backendless countersFor each entry in a given table, Backendless creates a unique objectId property – this is a UUID. In some cases, you may want to have a unique ID based on a whole number. To do this, we will use Backendless Atomic Counters (you can read the documentation about Atomic Counters here). In this article, we will use JavaScript business logic (Cloud Code) to create an event handler that will add a unique value before creating the object. You can then store that value in your table to provide the ID you’re looking for.

We’re going to take a step-by-step approach to this example.

  1. Create a table with the name Person.
  2. Create a column with the name id and the Unique Value and Not Null constraints.
    Create column in a Backendless table
  3. Add an event handler by visiting the Custom Business Logic (Cloud Code) section of Backendless Console.Add custom business logic event handler
  4. Change the code to the following:

    /**
    * @param {Object} req The request object contains information about the request
    * @param {Object} req.context The execution context contains an information about application, current user and event
    * @param {Person} req.item An item to create
    *
    * @returns {Person|Promise.<Person>|void} By returning a value you can stop further event propagation and return
    *          a specific result to the caller
    */
    Backendless.ServerCode.Persistence.beforeCreate('Person', function(req) {
     return Backendless.Counters.getAndIncrement( "PersonId" )
       .then( function( result ) {
         req.item.id = result
       })
    });
  5. To check that we did it right, go to Data -> Person table -> REST Console add a record to the table:Add a record to the table using REST console

That’s all it takes to add a unique, incremental ID to each object in your table.

Happy coding!

Leave a Reply