For 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.
/** * @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 }) });
That’s all it takes to add a unique, incremental ID to each object in your table.
Happy coding!
I do exactly that same with my index and I get this error. :/
{
“code”: 1364,
“message”: “Field ‘ID’ doesn’t have a default value”
}
I have table->Players with column->ID
Hi @MartinDan, could you show what the request looks like?
This only is executed if a row is inserted using a POST?
Is there a way insert a row directly in the DB and execute a before or after handler to set the counter?
Thnx
Executing POST or using the API in our SDKs is the only way to insert data into the database. There is no “direct insertion into the database” as the database is not exposed to the outside world
Works really well! Can you link the current value of the Atomic Counter to an APP Table?
For instance, I use one Atomic Counter that counts the number of Males (And one AC for Females).
The APP Table is “GenderCount” with a column “Gender” and “Count”
Gender Count
Male 0
Female 0
Then every time the Atomic Counter increments, I want to increment the “Count” column of “Male” too.