Question

I have an IndexedDB of changes. I add an item like this, and then log the result to check the key has been created successfully:

_this._idb.add('steps', step).done(function (items) {
        var item = items[0];
        _logger.log("ADDED STEP", { id: item.__id__, step: item }, "CT");
    });

The output from this is as expected:

enter image description here

...as you can see, the id has been added to the object when it is stored.

However, when I query the db to getback a list of objects, using this code:

this._idb.steps.query('timestamp').bound(start, end).execute().done(function (results) {
        _logger.log("Results", results, "CT");
    }

I don't get the id as part of the object that is returned:

enter image description here

... and the lack of id makes updating and deleting impossible.

How can I get the id of the item when I query indexed db using db.js - or am I approaching this in the wrong way, and is there something else I should be doing?

(Note: I'm using TypeScript to compile the JS, but I don't think that's especially relevant to this question)

Was it helpful?

Solution

This is expected behaviour, you're only going to get the __id__ property if you don't define a keyPath in your db schema.

Because there's no keyPath defined the value is not associated with it in indexeddb, it's only added to the resulting object after it has been added, because at that point in time we know the auto-incremented value that IndexedDB has assigned to it.

Since the value isn't really part of the object I don't have any way to assign it to the object when it comes out during a query, maybe I could use the position in the array but that's more likely to be wrong than right.

If you want the ID to be persisted against the object then you need to define a keyPath as part of the object store schema and the property will be added to the resulting object and available and it will be on the object returned from a query.

Disclaimer - I wrote db.js

OTHER TIPS

Looking at the source, __id__ is only defined when your keyPath is null in the add() method. From what I'm seeing, you'll never see this in a query() response.

In IDB null keyPaths are allowed only when using auto-incrementing ("out-of-line") keys. So if you're getting the object back, it should have an auto-incrementing key on it or some other keyPath.

The __ prefix in JavaScript usually means the developer intended it to be a "private" property. I'm guessing this is for internal use and you shouldn't be counting on this in your application code.

Consider using explicit, so-called "in-line" keys on your object store.

The goal of db.js is easy and simple to use. Your is advanced use case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top