NOTE: ScriptDB is now deprecated. Please take a look at Database abstraction with google apps script for alternatives.
Sometimes you need to create a unique identification for each object. ScriptDB automatically assigns a unique objectId for each object, so you can just use this. However, if you really do want to create a unique numeric ID that increments with each save, you can try this using this function to save to your scriptdb.
We're using the lock service. This will protect this section of code being run by multiple users at the same time while the next id is being calculated. We'll hold this for a maximum of 10 seconds.
db - the scriptDB to use. We'll pass this instead of using ScriptDb.getMyDb(). This will allow you to use the same function in a library to access multiple scriptDb.
ob - the object to write.
key - the name of the key to auto increment.
proto - an optional object that identifies the objects of this type (there may be more than one object type in this scriptDb). I always use a siloId to segregate all types of data.
Do a query on the current scriptDb content, returning a single record - sorting it in descending order will give us the current highest value.
The first record ever will receive id 1. Otherwise, it will increment the current value of ob[key].
Here's an example, writing 5 records to an existing database
and the results..
For more like this, see From VBA to Google Apps Script . Why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available.
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > From VBA to Google Apps Script > Using scriptDB >