indexedDB highest keypath

2020-04-29 17:05发布

问题:

I have a database inside indexedDB filled using an Emberjs adapter. I have set the keypath like this :

this.addModel(App.Device, { keyPath: 'key' });

And my key is autoincremented when I parse my data the first time I got them like this :

data = data.map(function( item, idx ) {
                item.key = idx;
                return item;
            });

After all of the data are store inside indexedDB, I want to add some more data, but I need to get to continue to set a key value inside my data.

How can I get the highest key (in my case it's a unique number (like an id)), so I can increment the one the key in my current data to add to my database ?

Here is the sample of my code that I want to use to add more data :

var request = indexedDB.open( 'products' );
            request.onsuccess = function( e ) {
                console.log('Success!');
                that.setProperties({ db: e.target.result });
                var db = e.target.result;
                var reader = new window.FileReader();
                reader.readAsDataURL(blob_);
                var img64;
                reader.onloadend = function() {
                    base64data = reader.result;
                    var dataImage = {
                        key: 42,
                        url: url_,
                        base64: base64data
                    }
                    that.storage.saveProduct( db, dataImage );
                }
            };

            request.onerror = function( e ) {
                console.log('Error!');
                console.dir( e );
            };

[edit] I forgot to put the saveProduct fct :

this.saveProduct = function( db, data ) {
        var transaction = db.transaction( ["App.Device"], "readwrite" );
        var store = transaction.objectStore( "App.Device" );

        var request = store.add( data );

        request.onerror = function( e ) {
            console.log("Error",e.target.error.name);
            //some type of error handler
        };

        request.onsuccess = function( e ) {
            console.log("Device saved in db");
        };
    };

回答1:

Here's an IDB pattern for the last entry:

  1. Bind your cursor value to the first ID entry. ("0" should do it since keys are lexicographically ordered.) (Original answer linked to question https://stackoverflow.com/a/22812410/317937 which has now been removed)
  2. Use a reverse cursor ("prev" or "prevunique" direction depending on your needs)
  3. Your next entry will be the last entry (skip() or continue() either should work)